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;
}
函数模版
类模版