加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

关于C++复制构造函数的实现讲解

发布时间:2020-12-15 04:51:30 所属栏目:百科 来源:网络整理
导读:复制构造函数是一种特殊的构造函数,有一般构造函数的特性。它的功能是用一个已知的对象来初始化一个被创建的同类对象。复制构造函数的参数传递方式必须按引用来进行传递,请看实例: #include #include using namespace std ; class Student { private : ch

复制构造函数是一种特殊的构造函数,有一般构造函数的特性。它的功能是用一个已知的对象来初始化一个被创建的同类对象。复制构造函数的参数传递方式必须按引用来进行传递,请看实例:

#include

#include

using namespace std ;

class Student

{

private :

char name[8];

int age ;

char sex ;

int score ;

public :

void disp(); //打印信息的函数声明

Student(char name[],int age,char sex,int score); //构造函数声明

Student(Student &dx); //复制构造函数的声明

~Student(); //析构函数的声明

};

//打印信息函数的实现

void Student::disp()

{

cout << this->name << endl ;

cout << this->age << endl ;

cout << this->sex << endl ;

cout << this->score << endl ;

}

//构造函数的实现

Student::Student(char name[],int score)

{

strcpy(this->name,name);

this->age = age ;

this->sex = sex ;

this->score = score ;

}

//复制构造函数的实现

Student::Student(Student &dx)

{

strcpy(this->name,dx.name);

this->age = dx.age ;

this->sex = dx.sex ;

this->score = dx.score ;

}

//析构函数的实现

Student::~Student()

{

cout << "程序结束" << endl ;

}

int main(void)

{

Student stu1("YYX",23,'N',86);

Student stu2(stu1);

stu1.disp() ;

stu2.disp() ;

return 0 ;

}

运行结果:

YYX


23


N


86


YYX


23


N


86


程序结束


程序结束

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程之家的支持。如果你想了解更多相关内容请查看下面相关链接

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读