菜鸟生成记(82)
创建构造函数带参数的对象数组(构造函数初始化列表)
两种写法;
(1)使用构造函数初始化列表,同时赋予默认值;创建对象数组比较简单
(2)使用构造函数进行成员赋值,不过创建对象数组,有点儿麻烦!
(1)
#include<iostream>
using namespace std;
class node{
public:
node(int a,int b);
~node();
void print();
private:
int x,y;
};
node::node(int a=0,int b=0):x(a),y(b)
{
;
}
node::~node()
{
cout<<"这个对象终结了!"<<endl;
}
void node::print()
{
cout<<x<<" "<<y<<endl;
}
int main()
{
node *t=new node;
t->print();
node *a=new node[10];
a[9].print();
delete []a;
delete t;
return 0;
}
(2)
#include<iostream>
using namespace std;
class node{
public:
node(int a,int b);
~node();
void print();
private:
int x,y;
};
node::node(int a,int b)
{
x=a,y=b;
}
node::~node()
{
cout<<"这个对象终结了!"<<endl;
}
void node::print()
{
cout<<x<<" "<<y<<endl;
}
int main()
{
node *t=new node(2,3);
t->print();
node *a=(node*)operator new(sizeof(node)*10);
for(int i=0;i<10;i++)
{
new(&a[i])node(1,2);
}
a[9].print();
delete []a;
delete t;
return 0;
}