【问题标题】:Using a struct variable inside a class constructor在类构造函数中使用结构变量
【发布时间】:2023-03-24 19:54:01
【问题描述】:
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)) {}

我有一个结构日期,其中包含 3 个变量日、月、年。 下面,在 Person 类中,我使用 Date 作为构造函数。但是当我设置日、月和年 = 0 时,它显示错误,我有那个表达式必须具有指向函数类型的指针?我的问题是什么?我该如何解决?

【问题讨论】:

    标签: c++ class struct


    【解决方案1】:

    编译器认为语法dOB.day(0)是一个函数调用。

    不用命名成员,你可以这样写:

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

    dOB 的每个成员都被初始化为 0。

    这是demo。

    【讨论】:

      【解决方案2】:

      将 CTOR 添加到您的 Date 结构中:

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

      使用它:

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

      或者:

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

      【讨论】:

        【解决方案3】:

        您的 Date 结构是 Aggregate type - 阅读 Aggregate

        您可以使用direct initialization 或list 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
        

        【讨论】:

          【解决方案4】:

          上面已经包含了两种初始化 dOB 结构的方法。

          但是,如果您只需要 Person 类的默认 ctor,您甚至不需要自己初始化 dOB,因为 int 将自动初始化为 0,而 dOb 将是自动初始化为{0, 0, 0}

          【讨论】:

            猜你喜欢
            • 2020-10-18
            • 1970-01-01
            • 1970-01-01
            • 2019-05-25
            • 2012-11-10
            • 2017-07-17
            • 2018-06-06
            • 2013-06-20
            • 1970-01-01
            相关资源
            最近更新 更多