[英]How to create member objects by class constructor?
In my example I created a class Person which has a member object: struct data.在我的示例中,我创建了一个类Person ,它有一个成员对象:struct data。 This object contains data about person.
此对象包含有关人员的数据。 Each time a Person-Object is created, also the data-object shall be initialized.
每次创建 Person-Object 时,也应初始化数据对象。
Observation: When adding object initializer to code (1) at class constructor I get failure message:观察:在类构造函数中将对象初始值设定项添加到代码 (1) 时,我收到失败消息:
incomplete type is not allowedC/C++(70)不允许不完整类型C/C++(70)
class person {
public:
struct data;
person() { /* (1) */
person::data myPersonData;
}
private:
};
So here is how I practice it now:所以这就是我现在练习的方法:
The whole example looks like this:整个示例如下所示:
// 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;
}
You should put the definition of data
inside the definition of person
if you want a member of it.你应该把定义
data
的定义里面person
,如果你想它的一个成员。 Something like this.像这样的东西。
#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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.