1. 程式人生 > 其它 >賦值運算子過載

賦值運算子過載

一個類預設建立時 預設構造、析構、拷貝構造和operator=賦值運算子過載(淺拷貝) 進行簡單的值傳遞

1.1 系統預設給類提供 賦值運算子寫法 是簡單值拷貝

1.2 導致如果類中有指向堆區的指標,就可能出現深淺拷貝的問題

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class Person
{
public:
    Person(int a)
    {
        this->m_A = a;
    }

    int m_A;
};

void test()
{
    Person p1(
10); Person p2(0); p2 = p1; //通過預設的operator= 進行淺拷貝 把p1的成員屬性複製給p2 cout << "p2.m_A = " << p2.m_A << endl; } int main() { test(); system("Pause"); return 0; }

結果:

1.3 所以要過載 = 運算子

1.4 如果想鏈式程式設計 return*this