对象数组与构造函数

来源:互联网 发布:linux如何卸载mysql 编辑:程序博客网 时间:2024/06/05 02:41

参考一

定义对象数组时,数组中的各个元素需要构造函数来初始化。数组能否定义成功,关键在于每个元素都有合适的构造函数,默认构造函数并不是必须的。

 

1.动态对象数组,对象所属类型必须有public默认构造函数.

2.静态对象数组

(1)没有提供初始化式的元素将调用默认构造函数来初始化

(2)提供初始化式的构造函数将调用相应的构造函数

#include <iostream>using namespace std;class Dog  {  public:  ~Dog();  Dog():name(0),age(0){}  Dog(int k):name(0),age(k){}  Dog(std::string* n,int a);  Dog(const Dog& dog);  private:  std::string* name;  int age;  };   Dog::~Dog()  {  delete name;  }   Dog::Dog(std::string* n,int a)  {  name=new std::string;  *name=*n;  age=a;  }    Dog::Dog(const Dog& dog)  {  name=new std::string;  *name=*(dog.name);  age=dog.age;  }   int main()  {  Dog doggy;     //动态对象数组     Dog* pDog=new Dog[10];//调用Dog::Dog()     //静态对象数组     Dog dogArr[3];//调用Dog::Dog()     string dogName="旺财";  Dog dogArr1[5]={Dog(&dogName,3),2,doggy};     //dogArr1[0]调用Dog::Dog(std::string* n,int a)进行初始化     //dogArr1[1]调用Dog::Dog(int k)进行初始化     //dogArr1[2]调用Dog::Dog(const Dog& dog)进行初始化     //其它调用默认构造函数进行初始化   return 0;  }


 

参考二

#include <iostream>using namespace std;class CElem{public:CElem(){cout<<"CElem Constructor...."<<endl;}};class CElem2{public:CElem2(const char* name){cout<<"CElem2 Constructor: "<<name<<endl;}};int main(int argc, char* argv[]){const int LEN = 5;CElem elems[LEN]; //用此方式来声明对象数组,对象一定要包含默认构造函数才行,并且在声明过程中会自动调用默认构造函数//CElem2 elems2[LEN]; //编译不过:error C2512: “CElem2”: 没有合适的默认构造函数可用system("pause");return 0;}/*Output:CElem Constructor....CElem Constructor....CElem Constructor....CElem Constructor....CElem Constructor....*/


 

原创粉丝点击