總結:
1、等號操作符過載和拷貝建構函式過載一般用在資料成員中需要單獨在堆區開闢記憶體時(指標)
2、new,delete過載內部還是使用malloc和free
3、逗號表示式(,)、或者(||),且(&&),條件表示式(?:)具有短路功能。
但過載後失去此功能,故不建議過載這兩個運算子
4、自定義智慧型指標auto_ptr(在c++11新特性中已經被移除)是乙個模板類。
可以自動被**,自動釋放
等號操作符過載:
#if 1
#define _crt_secure_no_warnings
#include using namespace std;
class student
student(int id, char *name)
student(const student& another)
student& operator=(const student& another)
//執行深拷貝
this->id = another.id;
this->name = new char[strlen(another.name) + 1];
strcpy(this->name, another.name);
return *this;
} void prints()
~student()
}private:
int id;
char *name;
};void test01()
/*id:1 name:zhangdan
id:1 name:zhangdan
*/int main()
#endif
new和delete操作符過載:
#if 1
#define _crt_secure_no_warnings
#include using namespace std;
class a
a(int a)
//過載的new操作符 依然會觸發物件的建構函式
void* operator new(size_t size)
void* operator new(size_t size)
void operator delete(void *p)
} void operator delete(void *p)
} ~a()
private:
int a;
};void test01()
/*過載new操作符
a(int)...
~a()....
過載了delete操作符
*/void test02()
/*過載new操作符
a()...
a()...
a()...
a()...
a()...
~a()....
~a()....
~a()....
~a()....
~a()....
過載了delete操作符
*/int main(void)
#endif
&&和||操作符過載(不建議使用,使用了短路功能):
#if 1
#define _crt_secure_no_warnings
#include using namespace std;
class test
test operator+(test &another)
bool operator&&(test &another)
else
} bool operator||(test &another)
else
} ~test()
private:
int value;
};void test01()
else }/*
執行了&&操作符過載
為假~test()...
~test()...
*/void test02()
cout << "a:" << a << endl;
test t1(0);
test t2(20);
//過載&&操作符,並不會發生短路現象。
if (t1 && (t1 + t2))
else }/*
a:0執行了+操作符過載
~test()...
執行了&&操作符過載
~test()...
為假~test()...
~test()...
*/void test03()
else }/*
執行了+操作符過載
~test()...
過載了||操作符
~test()...
為真~test()...
~test()...
*/int main(void)
#endif
自定義智慧型指標(stl中模板類,指標用完自動**,不需要手動delete):
#if 1
#includeusing namespace std;
#include//智慧型指標是自動被**,自動釋放
//只能指標是乙個模板類
class a
void func()
~a()
private:
int a;
};void test01()
void test02()
void test03()
/*a()...
a = 10
a = 10
~a()...
*/class myautoptr
~myautoptr()
} a* operator->()
a& operator*()
private:
a *ptr; //內部指標
};void test04()
/*a()...
delete ptr
~a()...
*/int main(void)
#endif
C 基礎 操作符過載
關於操作符過載,是c 乙個十分強大的功能。本文初略介紹下,涉及到友元以及函式過載 標頭檔案myclass.h ifndef myclass h define myclass h include include using namespace std class myclass myclass myc...
C 之操作符過載
1.所謂過載,就是賦予其新的意義。函式可以過載,操作符也可以過載。操作符的過載給我們的程式設計帶來了很大的便利,因為操作符只能對基本的資料型別進行操作,而對使用者自定義的類等資料結構型別不支援。因此只能對其操作符進行過載之後,才能更加方便地操作我們自定義的類物件等資料型別。但是值得注意的是並不是c ...
c 之操作符過載
include using namespace std class complex void printcom test add2 test t2 this 函式返回元素 complex operator complex c1 complex operator complex operator in...