在类构造函数中使用单独类的对象

Using an object of separate class in a class constructor

本文关键字:单独类 对象 构造函数      更新时间:2023-10-16

为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构造函数

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

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) {}