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

标签 c++ xcode object constructor member

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

关于c++ - 在类构造函数中使用单独类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33193114/

相关文章:

javascript - 计算特定键的数量

c++ - 为什么静态成员变量不能很好地与三元运算符一起使用?

c++ - 如何在不使用外部库的情况下使用 SDL 绘制线条

c++ - 为什么 std::vector 这么快(或者我的实现太慢了)

ios - Xcode 中的@1x、@2x 和@3x 图像大小应该是多少?

xcode - Swift,Equatable 协议(protocol)错误?

iphone - Obj-C @synthesize

javascript - 在javascript中声明和定义函数

javascript - 为什么 Date 不能被实例化为不是构造函数?以及其他困惑

java - 将 final 修饰符与 mutator 方法一起使用