简体   繁体   English

在 class 构造函数中使用结构变量

[英]Using a struct variable inside a class constructor

struct Date
{
    int year;
    int month;
    int day;
};

class Person
{
private:
    string firstName;
    string lastName;
    Date dOB;
public:
    Person();
    Person(const string& f, const string& l, const Date& d);
};

Person::Person() : firstName("None"), lastName("None"), dOB(dOB.day(0),dOB.month(0), dOB.year(0)) {}

I have a Struct Date with 3 variables day, month, year.我有一个结构日期,其中包含 3 个变量日、月、年。 Below, in the class Person, I am using Date for the constructor.下面,在 class Person 中,我使用 Date 作为构造函数。 But when I set the day, month and year = 0 it shows error that I have that expression must have pointer-to function type?但是当我设置日、月和年 = 0 时,它显示错误,我有那个表达式必须有指向 function 类型的指针? What is my problem here?我的问题是什么? How can I fix it?我该如何解决?

The compiler thinks the syntax dOB.day(0) is a function call.编译器认为语法dOB.day(0)是 function 调用。

Instead of naming the members, you can write it like this:您可以这样写,而不是命名成员:

Person::Person() : firstName("None"), lastName("None"), dOB{0,0,0} {}

where each member of dOB gets initialized to 0. dOB的每个成员都被初始化为 0。

Here's a demo .这是一个演示

Add a CTOR to your Date struct:将 CTOR 添加到您的Date结构中:

Date(int day, int month, int year) : year(year), month(month), day(day) {}

Use it:用它:

Person::Person() : firstName("None"), lastName("None"), dOB(0, 0, 0) {}

Or:或者:

Person::Person(const string& f, const string& l, const Date& d) : dOB(d) { /*...*/ };

Your Date struct is Aggregate type - read for Aggregate您的Date结构是Aggregate type - 读取Aggregate

you can use either direct initialization or list initialization您可以使用direct initializationlist initialization

Person::Person() : firstName("None"), lastName("None"), dOB(0, 0, 0) {} // direct initialization


Person::Person() : firstName("None"), lastName("None"), dOB{0, 0, 0} {} // list initialization

Aboves already included two ways of intializing your dOB struct.上面已经包含了两种初始化你的dOB结构的方法。

However if you only want a default ctor for your Person class, you don't even need to init dOB yourself, as int would be auto init to 0 , and dOb would be auto initialized to {0, 0, 0}但是,如果您只需要Person class 的默认 ctor,您甚至不需要自己初始化dOB ,因为int会自动初始化为0 ,而dOb会自动初始化为{0, 0, 0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM