【问题标题】:Using an object of separate class in a class constructor在类构造函数中使用单独类的对象
【发布时间】:2016-01-16 13:01:29
【问题描述】:

为 SquareValue 设置以下构造函数的正确方法是什么? 我收到以下错误:

“SquareValue 的构造函数必须显式初始化没有默认构造函数的成员“square””

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class Square {

public:
int X, Y;

Square(int x_val, int y_val) {
    X = x_val;
    Y = y_val;
}

};


class SquareValue {

public:

Square square;
int value;

SquareValue(Square current_square, int square_value) {
    square = current_square;
    value = square_value;
}
};

我曾计划将 Square() 构造函数传递给 SquareValue 构造函数。

【问题讨论】:

    标签: c++ xcode object constructor member


    【解决方案1】:

    在构造函数中不使用列表初始化语法初始化对象时,使用默认构造函数:

    SquareValue(Square current_square, int square_value) {
        square = current_square;
        value = square_value;
    }
    

    相当于:

    SquareValue(Square current_square, int square_value) : square() {
        square = current_square;
        value = square_value;
    }
    

    square() 是个问题,因为Square 没有默认构造函数。

    用途:

    SquareValue(Square current_square, int square_value) :
       square(current_square), value(square_value) {}
    

    【讨论】:

    • 或者将 Square 构造函数更改为 Square(int x_val = 0, int y_val = 0) 以便可以默认构造。
    • 谢谢,我对初始化语法进行了一些故障排除,但似乎没有理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多