我正在尝试按如下方式初始化堆分配对象:
class Ball {
int radius;
string colour;
};
int main(){
Ball *b = new Ball { radius = 5, colour = "red" };
}
想知道为什么这会给我一个错误? 谢谢
最佳答案
这不是在 C++ 中初始化对象的方式。
这是一种方法:
class Ball {
int radius;
string colour;
public:
// Define a Constructor
Ball(int _radius, const string &_colour)
: radius(_radius)
, colour(_colour)
{
}
};
int main(){
Ball *b = new Ball(5, "red");
delete b; // Don't forget to free it.
}
关于c++ - 初始化堆分配对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8103088/