在 class 构造函数中使用单独的 class 对象
Using an object of separate class in a class constructor
为 SquareValue 设置以下构造函数的正确方法是什么?
我收到以下错误:
"constructor for SquareValue must explicitly initialize the member "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) {}
为 SquareValue 设置以下构造函数的正确方法是什么? 我收到以下错误:
"constructor for SquareValue must explicitly initialize the member "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) {}