加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++之赋值运算符重载

发布时间:2020-12-16 09:06:02 所属栏目:百科 来源:网络整理
导读:c++编译器至少给一个类添加四个函数: 构造函数 析构函数 拷贝构造函数,对属性进行值拷贝; 赋值运算符,对属性进行值拷贝; #includeiostream using namespace std; class Person { public : Person( int age) { m_Age = new (age); } int * m_Age; ~ Pers

c++编译器至少给一个类添加四个函数:

  • 构造函数
  • 析构函数
  • 拷贝构造函数,对属性进行值拷贝;
  • 赋值运算符,对属性进行值拷贝;
#include<iostream>
using namespace std;
class Person {
public:
    Person(int age) {
        m_Age = new (age);
    }
    int* m_Age;
    ~Person() {
        if (m_Age != NULL) {
            delete m_Age;
            m_Age = NULL;
        }
    }
    //这里需要使用引用,如果不用相当于利用拷贝函数新建了个对象
    Person& operator=(Person& p) {
        应该先判断是否有属性在堆区,如果有,则先释放干净,然后再进行深拷贝
         NULL;
        }
        m_Age = int(*p.m_Age);
        return *this;

    }
};
void test() {
    Person p1(18);
    Person p2(20);
    Person p3(22);
    p3 = p2 = p1;赋值操作
    cout << "p1的年龄是:" << *p1.m_Age << endl;
    cout << p2的年龄是:" << *p2.m_Age <<p3的年龄是:" << *p3.m_Age << endl;
}


 main() {
    test();
    system(pause");
    return 0;
}

输出:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读