关于类的数组初始化后会调用拷贝构造函数?
这段代码,我的问题是:为什么在初始化类的对象时,只有在类的数组对象初始化时才会调用拷贝构造函数?并且当我把类的数组对象初始化时的字符串string的"张三"去掉时,就不会调用。我用VS2010调试时,发现初始化的成员会在调用完自身的构造函数后会直接调用拷贝构造函数
程序代码:
#include <iostream> #include<string> using namespace std; class Student { private: int MathScore,CScore,EnglishScore; public: long stuNo; string stuName; char stuSex; void setScore(int mathScore,int cScore,int englishScore) { MathScore=mathScore; CScore=cScore; EnglishScore=englishScore; } void display(); Student(string stuname) {stuNo=122301002;stuName=stuname;stuSex='F';} Student(long stuno) {stuNo=stuno;stuName="张三";stuSex='F';} Student(long stuno, string name) { stuNo=stuno;stuName=name;stuSex='F'; } Student(long stuno, string name,char sex) {stuNo=stuno;stuName="123";stuSex=sex;} Student(const Student &s) { cout<<"拷贝构造函数的调用" ; stuNo=s.stuNo; stuName=s.stuName; stuSex=s.stuSex; MathScore=s.MathScore; CScore=s.CScore; EnglishScore=s.EnglishScore; } }; void Student::display(){ cout<<"学生信息如下:"<<endl; cout<<"学号:"<<"\t\t姓名:"<<"\t性别:"<<"\t数学:"<<"\tC语言:"<<"\t英语:"<<endl; cout<<stuNo<<"\t"<<stuName<<"\t"<<stuSex<<"\t"<<MathScore<<"\t"<<CScore<<"\t"<<EnglishScore<<endl; } int main(void) { cout<<"测试1"; Student stu[4]={ Student("张三"),Student(122301002),Student(122302003,"赵五"),Student(122302004,"李四",'F')}; cout<<"测试2"; stu[0].setScore(80,87,56); stu[1].setScore(81,84,58); stu[2].setScore(80,90,53); stu[3].setScore(80,82,55); for (int i=0;i<4;i++) { stu[i].display(); } Student stus("张三"); stus.display(); return 0; }
[ 本帖最后由 hutianlun 于 2014-4-17 11:17 编辑 ]