【问题标题】:Constructor of a class with an attribute that is another class object具有另一个类对象的属性的类的构造函数
【发布时间】:2019-03-14 06:04:32
【问题描述】:

构造函数声明:

Funcion(std::string cveFunc=" ", int numP = 0, Hora hour(0,0), int room=0);

构造函数:

Funcion::Funcion(std::string cveFunc, int numP, Hora hour(), int room) : 
    cveFuncion{cveFunc}, numPeli{numP}, hora hour = {}, sala{room}{}

问题在于属性hour我不知道如何正确声明。

这是 hora 类的构造函数:

课内:

Hora(int hhh=0, int mmm=0);

课外:

Hora::Hora(int hhh, int mmm) : hh{hhh}, mm{mmm} {}

【问题讨论】:

  • 声明中Hora hour(0, 0)不正确;如果你想提供一个默认值,你需要Hora hour = Hora(0, 0)
  • 首选全英文标识符,很可能您将与其他人共享代码(如果它只是在这里...)并且您不能期望每个人都能理解母语(或者会您会立即期望Uhrzeithora 相同?)。承认,在给定的情况下猜测非常简单,但在更复杂的情况下......此外,我认为这种语言的狂野混合是不美观的。

标签: c++ object constructor attributes declaration


【解决方案1】:

使用

Funcion::Funcion(std::string cveFunc, int numP, Hora hour(), int room)

是错误的,因为在这种情况下hour 被声明为一个不带参数并返回Hour 的函数。您需要删除()。使用:

Funcion::Funcion(std::string cveFunc, int numP, Hora hour, int room)

假设hora是类的成员变量,那么成员初始化也需要更新为:

cveFuncion{cveFunc}, numPeli{numP}, hora {hour}, sala{room}

综合起来,你有:

Funcion::Funcion(std::string cveFunc, int numP, Hora hour, int room) :
        cveFuncion{cveFunc}, numPeli{numP}, hora {hour}, sala{room}{}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多