C++复制构造函数的实现

xiaoxiao2021-02-28  128

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

#include <iostream> #include <cstring> 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 age , char sex ,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

程序结束

程序结束

Engineer-Bruce_Yang 认证博客专家 嵌入式硬件 单片机 arm开发 本科毕业于华南理工大学,现美国卡罗尔工商管理硕士研究生在读,曾就职于世界名企伟易达、联发科技等,多年嵌入式产品开发经验,在智能玩具、安防产品、平板电脑、手机开发有丰富的实战开发经验,现任深圳市云之手科技有限公司副总经理、研发总工程师。
转载请注明原文地址: https://www.6miu.com/read-58099.html

最新回复(0)