static成員函數、數據成員;運算符重載

static

數據成員初始化語法:類型  類名::數據成員名=?//int tank::count=0;

調用方法:1、類名::數據成員名2、對象名.數據成員名

特點:1、只屬於類,最好在類外單獨初始化2、只能被靜態成員函數訪問,靜態成員函數,不能調用非靜態成員函數和數據成員3、不屬於任何對象,屬於類


運算符重載

一元運算符重載:只對一個操作數操作(如-,負號,++)

方式兩種:成員函數、友元函數

成員函數式重載

#include<iostream>
using namespace std;

class c{
	int x, y;
public:
	c(int xx, int yy) :x(xx), y(yy){}
	c& operator -();//負號,一元重載運算符語法,成員函數式重載,返回值類型(類型+&) +函數名(關鍵字operator+運算符)
};
c& c::operator-(){
	x = -x;
	y = -y;
	return *this;
}
int main(){
	c c1(1, 2);
	-c1;//等價於c1.operator-();
	
	system("pause");
	return 0;
}
友元函數式重載

#include<iostream>
using namespace std;

class c{
	int x, y;
public:
	c(int xx, int yy) :x(xx), y(yy){}
	friend c& operator -(c &c1);//負號,一元重載運算符語法,成員函數式重載,返回值類型(類型+&) +函數名(關鍵字operator+運算符)
	void display(){ cout << x << "," << y << endl; }
};
c& operator-(c &c1){
	c1.x = -c1.x;
	c1.y = -c1.y;
	return c1;//注意不能是返回this了
}
int main(){
	c c1(1, 2);
	-c1;//等價於c1.operator-();
	c1.display();
	system("pause");
	return 0;
}
二元運算符重載方式:成員函數,友元函數

#include<iostream>
using namespace std;

class c{
	int x, y;
public:
	c(int xx=0, int yy=0) :x(xx), y(yy){}
	c operator+(const c &c1);
	void display(){ cout << x << "," << y << endl; }
};
c c:: operator+(const c &c1){//默認了第一個參數就是當前類的對象
	c t;
	t.x = this->x + c1.x;
	t.y = this->y + c1.y;
	return t;
}
int main(){
	c c1(1, 2);
	c c2(2,3);
	c2 = c1 + c2;//等價與c1.operator+(c2)
	c2.display();
	system("pause");
	return 0;
}
友元函數式重載

#include<iostream>
using namespace std;

class c{
	int x, y;
public:
	c(int xx=0, int yy=0) :x(xx), y(yy){}
	friend c operator+(const c &c1,const c &c2);
	void display(){ cout << x << "," << y << endl; }
};
c operator+(const c &c1, const c &c2){
	c t;
	t.x = c1.x + c2.x;
	t.y = c1.y + c2.y;
	return t;
}
int main(){
	c c1(1, 2);
	c c2(2,3);
	c2 = c1 + c2;//operator+(c1,c2)
	c2.display();
	system("pause");
	return 0;
}

輸出運算符重載<<,不能用成員函數重載,因爲ostream不能是屬於當前某一個類的

#include<iostream>
using namespace std;

class c{
	int x, y;
public:
	c(int xx=0, int yy=0) :x(xx), y(yy){}
	friend ostream& operator <<(ostream &out,const c &c1);
	void display(){ cout << x << "," << y << endl; }
};
ostream& operator <<(ostream &out, const c &c1){
	out << c1.x << "," << c1.y << endl;
	return out;
}
int main(){
	c c1(1, 2);
	c c2(2,3);
	cout << c2;//等價於operator<<(cout,c1)
	system("pause");
	return 0;
}
索引運算符,不能用友元實現,因爲第一個參數一定是this指針

#include<iostream>
using namespace std;

class c{
	int x, y;
public:
	c(int xx=0, int yy=0) :x(xx), y(yy){}
	int operator[](int dex);
	void display(){ cout << x << "," << y << endl; }
};
int c::operator[](int dex){
	if (dex == 0)
		return x;
	if (dex == 1)
		return y;
	else
		cout << "wrong" << endl;
}
int main(){
	c c1(1, 2);
	c c2(2,3);
	cout << c2[0];//c2.operator[](0)
	system("pause");
	return 0;
}

函數模版


類模版









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章