1.拷贝构造函数2.调用父类的拷贝构造函数3.拷贝构造函数与浅拷贝
1.拷贝构造函数拷贝构造函数是构造函数的一种。
当利用已存在的对象创建一个新对象时(类似于拷贝),就会调用新对象的拷贝构造函数进行初始化。
拷贝构造函数的格式是固定的,接收一个const引用作为参数。
#includeusing namespace std; class Car { public: int m_price; int m_length; Car(int price = 0, int length = 0) : m_price(price), m_length(length) { cout << "Car(int price = 0, int length = 0)" << endl; } void display() { cout << "price = " << m_price << ", length = " << m_length << endl; } }; int main() { Car car1(100, 5); Car car2(car1); car2.display(); getchar(); return 0; }
#include2.调用父类的拷贝构造函数using namespace std; class Car { public: int m_price; int m_length; Car(int price = 0, int length = 0) : m_price(price), m_length(length) { cout << "Car(int price = 0, int length = 0)" << endl; } // 拷贝构造函数 Car(const Car &car) : m_price(car.m_price), m_length(car.m_length) { cout << "Car(const Car &car)" << endl; } void display() { cout << "price = " << m_price << ", length = " << m_length << endl; } }; int main() { Car car1(100, 5); Car car2(car1); car2.display(); getchar(); return 0; }
#include3.拷贝构造函数与浅拷贝using namespace std; class Person { public: int m_age; Person(int age = 0) : m_age(age) {} Person(const Person &person) : m_age(person.m_age) {} }; class Student : public Person { public: int m_score; Student(int age = 0, int score = 0) : Person(age), m_score(score) {} Student(const Student &student) : Person(student), m_score(student.m_score) {} }; int main() { Student stu1(18, 100); Student stu2(stu1); cout << stu2.m_age << endl; // 18 cout << stu2.m_score << endl; // 100 getchar(); return 0; }
#includeusing namespace std; class Car { int m_price; int m_length; public: Car(int price = 0, int length = 0) : m_price(price), m_length(length) { cout << "Car(int price = 0, int length = 0)" << endl; } Car(const Car &car) : m_price(car.m_price), m_length(car.m_length) { cout << "Car(const Car &car)" << endl; } void display() { cout << "price = " << m_price << ", length = " << m_length << endl; } }; int main() { Car car1(100, 5); // Car(int price = 0, int length = 0) Car car2(car1); // Car(const Car &car) Car car3 = car2; // Car(const Car &car) Car car4; // Car(int price = 0, int length = 0) car4.display(); // price = 0, length = 0 // 这里并没有调用拷贝构造函数(仅仅是简单的赋值操作,默认是浅拷贝) car4 = car3; car4.display(); // price = 100, length = 5 getchar(); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)