c++ - 错误 : 'new' cannot appear in a constant-expression

标签 c++

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/

相关文章:

c++ - 你如何在 Xcode 6 中更新文件路径

c++ - 'this' 参数的类型为 const 但函数未标记为 const C++ 重载运算符

c++ - iPhone TCP-IP 字节顺序映射?

具有明确舍入策略的整数除法 C++ 函数

c++ - 使用 foreach 将多个 wxTextCtrl 的标签设置为空值

c++ - filebuf::openprot 的用途是什么,它有替代品吗?

c++ - C++ 头文件中空引用驱动的段错误

c++ - C++11 lambda 的参数/存储类型

c++ - 对临时对象成员的 const 引用

c++ - 在循环中执行移位操作时 C++ 中的内存泄漏