C++中所有的 类型 变量都是 类 对象的形式,那么C++中类对象之间是怎么进行赋值操作的呢?
主要是因为C++存在拷贝构造函数,拷贝构造函数的定义如下所示:
类名(类名 &);
具体的实例如下所示:
#include <iostream> using namespace std; class Date { public: Date(int y, int m, int d); // 构造函数 Date(const Date &date1); // 拷贝构造函数 void showDate(); private: int year; int month; int day; }; Date::Date(int y, int m, int d) { year = y; month = m; day = d; cout << "调用构造函数" << endl; } Date::Date(const Date &date1) { year = date1.year; month = date1.month; day = date1.day; cout << "调用拷贝构造函数" << endl; } void Date::showDate() { cout << year << "." << month << "." << day << endl; } int main() { Date d1(2018, 5, 20); d1.showDate(); Date d2 = d1; d2.showDate(); return 0; } 显示结果为: 调用构造函数 2018.5.20 调用拷贝构造函数 2018.5.20
如果在类中没有自定义拷贝构造函数,则默认的的构造函数的作用是:不同对象的数据成员之间进行赋值操作。
拷贝构造函数使用注意事项:当类中的数据成员存在指针时,使用默认的赋值运算符函数进行对象赋值时,可能会产生错误。
文章来源: 为什么C++中的对象之间能够进行赋值?