【问题标题】:How to create member objects by class constructor?如何通过类构造函数创建成员对象?
【发布时间】:2020-10-22 09:18:23
【问题描述】:

在我的示例中,我创建了一个具有成员对象的类 Person:结构数据。此对象包含有关人员的数据。每次创建 Person-Object 时,也应初始化数据对象。

观察:在类构造函数中将对象初始化程序添加到代码 (1) 时,我收到失败消息:
incomplete type is not allowedC/C++(70)

class person {
public:
  struct data;
  person() { /* (1) */
    person::data myPersonData;
  }

private:
};

这就是我现在的练习方式:

  1. person 类构造函数 (class_person.hpp) 中没有结构对象初始化 myPersonData
  2. 在 main.cpp 中创建人员对象
  3. 在 main.cpp 中创建 myPersonData(我想保存这个 初始化并把它交给类构造器)

整个示例如下所示:

// class_person.hpp
    
    #include <iostream>
    #include <string>
    
    class person {
    public:
      struct data;
    
    private:
    };
    
    struct person::data {
      std::string name = "John";
      int age = 42;
      int weight = 75;
    };

_

// main.cpp

#include <iostream>

#include "class_person.hpp"

void outputPersonData(person::data myPerson) {
  std::cout << myPerson.name << "\n";
  std::cout << myPerson.age << "years\n";
  std::cout << myPerson.weight << "kg\n";
};

int main() {
  person John;
  person::data myPersonData;
  outputPersonData(myPersonData);
  getchar();
  return 0;
}

【问题讨论】:

  • struct data; 只是声明person::data;该结构缺少定义,因此不完整

标签: c++ class constructor


【解决方案1】:

如果你想要它的成员,你应该把data 的定义放在person 的定义中。像这样。

#include <string>
#include <iostream>

class person {
public:
    struct data {
        std::string name = "John";
        int age = 42;
        int weight = 75;
    };
    // This is just the definition the the class. We need the class
    // to have a definition if we want to use a value of it in person

    person() = default;
    // Default constructors, give us a default constructed personData
    // that uses the default values from the definition

    person(data d) : personData(std::move(d)) {}
    // Constructor that takes a personData object and uses it to
    // initialize our member. std::move is to avoid uneccesary copying

    void outputPersonData() const {
        std::cout << personData.name << "\n";
        std::cout << personData.age << "years\n";
        std::cout << personData.weight << "kg\n";
    }

    data personData;
    // This is the actual data member, now person contains
    // a member named personData of type person::data
};

int main() {
    person john;
    person mike({"Mike", 47, 82});

    john.outputPersonData();
    mike.outputPersonData();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 2011-11-10
    相关资源
    最近更新 更多