【c++】一个空类所具有的6个成员函数
C++中一个空类虽然没有数据成员,但编译器会为它自动生成六个特殊成员函数,即:
- 缺省构造函数
- 拷贝构造函数
- 析构函数
- 赋值运算符重载
- 取址运算符重载(非 const 版本)
- 取址运算符重载(const 版本)
下面是一个示例代码:
#include <iostream>
using namespace std;
class Empty {
public:
// 缺省构造函数
Empty() {
cout << "Default constructor called" << endl;
}
// 拷贝构造函数,参数用const引用防止修改原对象
Empty(const Empty&) {
cout << "Copy constructor called" << endl;
}
// 析构函数
~Empty() {
cout << "Destructor called" << endl;
}
// 赋值运算符
Empty& operator=(const Empty&) {
cout << "Assignment operator called" << endl;
return *this;
}
// 取址运算符(非 const 版本)
Empty* operator&() {
cout << "Address-of operator (non-const) called" << endl;
return this;
}
// 取址运算符(const 版本)
const Empty* operator&() const {
cout << "Address-of operator (const) called" << endl;
return this;
}
};
int main() {
cout << "Creating e1:" << endl;
Empty e1; // 调用缺省构造函数
cout << "\nCopy constructing e2 from e1:" << endl;
Empty e2(e1); // 调用拷贝构造函数
cout << "\nAssigning e3 = e1:" << endl;
Empty e3;
e3 = e1; // 调用赋值运算符
cout << "\nTaking address of e1 (non-const):" << endl;
Empty* p1 = &e1; // 调用取址运算符(非 const版本)
cout << "p1 = " << p1 << endl;
cout << "\nTaking address of e1 (const):" << endl;
const Empty* p2 = static_cast<const Empty*>(&e1); // 调用const版本的取址运算符
cout << "p2 = " << p2 << endl;
cout << "\nExiting main" << endl;
return 0;
}
ps:
赋值运算符重载函数 返回*this 它本身
取址运算符重载返回 this 它的地址
说明
-
默认构造函数
当定义对象Empty e1;
时,编译器调用了缺省构造函数(输出 “Default constructor called”)。 -
拷贝构造函数
当用e1
来初始化e2
(语句Empty e2(e1);
)时,调用了拷贝构造函数(输出 “Copy constructor called”)。 -
赋值运算符
当先创建了对象e3
(调用默认构造函数),再执行e3 = e1;
时,调用了赋值运算符(输出 “Assignment operator called”)。 -
取址运算符
使用表达式&e1
时,会调用我们重载的取址运算符(非 const 版本);若对象为 const 或在 const 上下文中,则调用 const 版本。这里我们分别通过Empty* p1 = &e1;
和用static_cast<const Empty*>(&e1)
显式转换为 const 指针来观察调用情况。 -
析构函数
当main
函数结束时,对象e1
、e2
和e3
都将被销毁,调用析构函数(会依次输出 “Destructor called”)。
通过这个示例,我们可以直观地看到即使一个空类没有任何数据成员,编译器在需要时仍会提供默认的构造、拷贝、赋值、取址和析构等六大函数,从而保证对象能够正确创建、复制、赋值、取地址和销毁。