在类构造函数中使用单独类的对象
Using an object of separate class in a class constructor
为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++中访问int到类对象的映射时出错
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 从父类方法返回子类对象
- 试图理解类对象的行为
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 将父类对象强制转换为子类的问题
- 类对象数组的问题会导致崩溃
- 对具有动态分配的内存和析构函数的类对象的引用
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 使用循环创建类对象
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- C++ 在堆栈中包含多态属性的类对象存储
- C++:跟踪类对象
- 链表包含 c++ 中不同的派生类对象
- 我们可以通过 IPC 传递具有动态管理成员的类对象吗?
- C++ 类对象作为函数参数
- 如何在 QML 中访问C++类对象,而不是在 QML 中创建单独的对象
- 在main()之前,在单独的文件中初始化/准备类对象
- 在类构造函数中使用单独类的对象