class A
{
int data;
public:
void display()
{
cout<<"Value is "<<data;
}
void set_data(int x)
{
this->data = x;
}
A object = new A();
};
当我运行上面的代码时,我收到错误消息“new cannot appear in constant expression”。为什么会这样?
最佳答案
接线员 new返回一个指针,但 A
不是指针类型。你想要 A*
:
A* object = new A();
你还想移动上面的statement在类主体之外并将其放入适当的函数中,例如 main()
:
int main() {
A* p = new A();
// do work
delete p;
}
也就是说你要么根本不需要指针,你可以简单地使用一个具有自动存储持续时间的对象:
A object;
或者您想考虑使用智能指针,例如 std::unique_ptr :
std::unique_ptr<A> p = std::make_unique<A>();
关于c++ - 错误 : 'new' cannot appear in a constant-expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51207199/