search

Home  >  Q&A  >  body text

class - c++中不能用new创建一个类的对象数组??

include <iostream>

using namespace std;
class text
{
public:

text(int m,int n): a(m),b(n){}
int a;
int b;

};

int main()
{

**text *p=new text[2]**;/*用p指向创建的对象数组*/
...
return 0;

}

尝试用以上代码用new创建一个对象数组,发现不行,是哪里不对吗?
为什么用new又可以为结构体创建对象数组?

黄舟黄舟2882 days ago730

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 12:59:50

    Try adding a parameterless constructortext(){}

    reply
    0
  • 阿神

    阿神2017-04-17 12:59:50

    Agree with Dappur's answer, you did not define a default constructor in the class. Your new text[2] statement was actually changed by the compiler to new text()[2], and it reported an error when it couldn't find it. I believe the compiler error says the same thing.

    reply
    0
  • Cancelreply