注册 登录
编程论坛 C++教室

对象数组动态分配时怎么初始化?

troyzyc 发布于 2018-04-11 10:01, 1853 次点击
//对象数组的动态分配+初始化+构造函数,这里到底是哪里出错了?
#include<iostream>
using namespace std;

class Square
{
public:
     double a;
     double Area();
     Square(double x); //构造函数
     ~Square();
};

double Square::Area()
{
    return a*a;
}

Square::Square(double x) //构造函数
{
    a=x;
}

Square::~Square()
{
    cout<<"array ends"<<endl;
}

int main()
{
    Square *q=new Square[3];  //我想申请一个Square类 类型的动态数组,有3个元素。 但这里总是报错!!不知道为什么?
    q[0]=Square(2);
    q[1]=Square(3);  //通过构造函数把初始值3 赋值给q[1]对象中的数据成员a
    q[2]=Square(4);

    for(int i=0;i<3;i++)
    {
        cout<<q[i].a<<"\t"<<q[i].Area()<<endl;
    }
    delete[]q;
    return 0;
}
2 回复
#2
rjsp2018-04-11 12:39
Square *q = new Square[3]
中构造 Square 的参数是什么,也就是调用 Square::Square(double x) 时这个x值是多少?

方法一:添加缺省构造函数,其它保持不变
class Square
{
public:
    explicit Square( double length=0 ) : length(length)
    {
    }
    double Area() const
    {
        return length*length;
    }

    double length;
};

#include <iostream>
using namespace std;

int main( void )
{
    Square* p = new Square[3];
    p[0] = Square(2);
    p[1] = Square(3);
    p[2] = Square(4);

    for( size_t i=0; i!=3; ++i )
        cout << p[i].length << '\t' << p[i].Area() << endl;

    delete[] p;
}

方法二:不添加缺省构造函数,new[]时指定参数
class Square
{
public:
    explicit Square( double length ) : length(length)
    {
    }
    double Area() const
    {
        return length*length;
    }

    double length;
};

#include <iostream>
using namespace std;

int main( void )
{
    Square* p = new Square[3]{ Square(2), Square(3), Square(4) };

    for( size_t i=0; i!=3; ++i )
        cout << p[i].length << '\t' << p[i].Area() << endl;

    delete[] p;
}

其实,我一直想说,C++中有 std::unique_ptr等,有 std::vector等,为什么你要自己new?


[此贴子已经被作者于2018-4-11 12:42编辑过]

#3
Jonny02012018-04-11 17:20
程序代码:
int main()
{
    Square **q=new Square *[3];  //我想申请一个Square类 类型的动态数组,有3个元素。 但这里总是报错!!不知道为什么?
    q[0]=new Square(2);
    q[1]=new Square(3);  //通过构造函数把初始值3 赋值给q[1]对象中的数据成员a
    q[2]=new Square(4);

    for(int i=0;i<3;i++)
    {
        cout<<q[i]->a<<"\t"<<q[i]->Area()<<endl;
    }
    for(auto i = 0; i < 3; i++) {
        delete q[i];
    }
    delete []q;
    return 0;
}

第一个指针指向数组
第二个指针指向对象
1