C++基礎知識,運算符重載

h:
#ifndef TESTCLASS__H
#define TESTCLASS__H

class testClass
{
public:
int a;
int b;
int c;
char* p;
//無參構造函數
testClass();
//運算符重載
testClass& operator=(const testClass&);
//構造函數
testClass(int, int, int);
//析構函數
~testClass();
};

#endif // !TESTCLASS__H

cpp:
#include
#include “testClass.h”
testClass& testClass::operator=(const testClass& sourceObj)
{
this->a = sourceObj.a;
this->b = sourceObj.b;
this->c = sourceObj.c;
std::cout << “調用了賦值運算符重載” << std::endl;
return *this;
}

testClass::~testClass()
{
delete[] p;
std::cout << “調用了析構函數” << std::endl;
}

testClass::testClass(int a, int b, int c) :a(a), b(b), c©
{

}

testClass::testClass()
{
char* p = new char[100];
}

mian
:
#include
#include “testClass.h”
using namespace std;

int main()
{
testClass classA(1, 2, 3);
testClass classB{ 4,5,6 };
//報錯,兩個對象不能這樣比較,需要重載運算符“==”
//if (classA == classB){}
//重載運算符本質上是一個"成員函數",是屬於對象的,而非類的。這個函數的正式名字:operator關鍵字 接運算符
//既然本質上是一個函數,那麼就有參數列表和返回參數
//有一些運算符,系統默認會生成一個運算符的重載,比如賦值運算符“=”
testClass classC = classA;//這是定義的時候初始化,不是賦值
testClass classD = { 7,8,9 };
classD = classC;

//2、拷貝賦值運算符
//testClass& operator=(const testClass&);
// 這個參數就是運算符右邊的對象,給一個const是爲了避免修改了右邊的對象
//testClass& testClass::operator=(const testClass&)
//{
// std::cout << “調用了賦值運算符重載” << std::endl;
// return *this;
//}

//3、析構函數,~className,沒有有參數,沒有返回值,不能重載 (就是java裏面的多態)
//析構函數幹了兩個事情,我們的寫的函數體部分,函數體執行完之後系統進行銷燬
//成員變量的初始化和銷燬的時機
//初始化順序:聲明的順序,先定義的變量先有值
//銷燬順序:先定義的後銷燬
//應該是個棧,先進後出,就是個棧
//但是如果是自己聲明的內存,如這個char* p = new char[100],就要顯示delete[] p;

//new/delete對象,new的對象一定要自己釋放
testClass* class1 = new testClass;//調用無參構造函數
testClass* class2 = new testClass();//調用無參構造函數
delete class1;//必須自己delete,然後程序纔會調用析構函數,這是放到了堆裏面
delete class2;

}

發佈了157 篇原創文章 · 獲贊 167 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章