C++构造函数的三种写法
上文提到,C++的三种构造函数:
- 无参构造函数:以类名作为函数名,没有形参;
- 一般构造函数:有初始化列表方式 和 内部赋值方式两种;
- 复制构造函数:根据一个已存在的对象复制出一个新的对象。
C++的 等号运算符重载 有点类似复制构造函数,将等号(=)右边的本类对象的值复制给等号左边的对象。
注意:等号运算符重载 不是构造函数,等号左右两边的对象必须已经被创建。
运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。
与其他函数一样,重载运算符有一个返回类型和一个参数列表。
等号运算符重载,示例代码如下:
#include using namespace std;class Student {public: int m_age; // 无参构造函数 Student() { m_age = 10; cout << "无参构造函数" << endl; } // 复制构造函数 Student(const Student& s) { m_age = s.m_age; cout << "复制构造函数" << endl; } // 等号运算符重载 Student &operator=(const Student& s) { cout << "等号运算符重载" << endl; // 如果是对象本身, 则直接返回 if (this == &s) { return *this; } // 复制等号右边对象的成员值到等号左边对象的成员 this->m_age = s.m_age; return *this; }};int main(){ Student stu1; // 调用无参构造函数 Student stu2(stu1); // 调用复制构造函数 printf("stu1: %d, stu2: %d", stu1.m_age, stu2.m_age); stu2.m_age = 22; stu1 = stu2; // 等号运算符重载 printf("stu1: %d, stu2: %d", stu1.m_age, stu2.m_age); return 0;}
运行结果为: