【c++】一个空类所具有的6个函数

【c++】一个空类所具有的6个成员函数

C++中一个空类虽然没有数据成员,但编译器会为它自动生成六个特殊成员函数,即:

  1. 缺省构造函数
  2. 拷贝构造函数
  3. 析构函数
  4. 赋值运算符重载
  5. 取址运算符重载(非 const 版本)
  6. 取址运算符重载(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 它的地址

说明

  1. 默认构造函数
    当定义对象 Empty e1; 时,编译器调用了缺省构造函数(输出 “Default constructor called”)。

  2. 拷贝构造函数
    当用 e1 来初始化 e2(语句 Empty e2(e1);)时,调用了拷贝构造函数(输出 “Copy constructor called”)。

  3. 赋值运算符
    当先创建了对象 e3(调用默认构造函数),再执行 e3 = e1; 时,调用了赋值运算符(输出 “Assignment operator called”)。

  4. 取址运算符
    使用表达式 &e1 时,会调用我们重载的取址运算符(非 const 版本);若对象为 const 或在 const 上下文中,则调用 const 版本。这里我们分别通过 Empty* p1 = &e1; 和用 static_cast<const Empty*>(&e1) 显式转换为 const 指针来观察调用情况。

  5. 析构函数
    main 函数结束时,对象 e1e2e3 都将被销毁,调用析构函数(会依次输出 “Destructor called”)。

通过这个示例,我们可以直观地看到即使一个空类没有任何数据成员,编译器在需要时仍会提供默认的构造、拷贝、赋值、取址和析构等六大函数,从而保证对象能够正确创建、复制、赋值、取地址和销毁。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值