C++基礎(chǔ)
重載
- 哪些運算符可以被重載:::,.,->,*,?:不能被重載
- 重載操作符的標(biāo)志(operator)
#include <iostream>
using namespace std;
int a1=12,b1=13,c1;
class test
{
int m_z;
public:
test(int z)
{
m_z=z;
}
test()
{
m_z=10;
}
int getz()
{
return m_z;
}
void setz(int z)
{
m_z=z;
}
};
test a2(10),b2(5),c2;
test operator+(test t1,test t2)
{
return t1.getz()+t2.getz();
}
int main(int argc,char **argv)
{
c1=a1+b1;//operator+(a1,b1);=>operator+(int i1,int i2);
c2=a2+b2;//operator+(a2+b2);=>operator+(test t1,test t2);//這樣編不過
cout<<"c1="<<c1<<endl;
cout<<"c2="<<c2.getz()<<endl;
}
/*
int operator+(test t1,test t2)
{
return t1.getz()+t2.getz();
}
c1=a2+b2;//operator+(a2+b2);=>operator+(test t1,test t2);//這樣編不過
cout<<"c1="<<c1<<endl;*/
#include <iostream>
using namespace std;
int a1=12,b1=13,c1;
class test
{
int m_z;
public:
test(int z)
{
m_z=z;
}
test()
{
m_z=10;
}
int getz()
{
return m_z;
}
void setz(int z)
{
m_z=z;
}
int operator+(test t2)//作為成員的運算符比之作為非成員的運算符墨林,在聲明和定義時蔫浆,形式上少一個參數(shù)谬返。
{
return m_z+t2.m_z;
}
};
test a2(10),b2(5),c2;
int main(int argc,char **argv)
{
c1=a1+b1;//operator+(a1,b1);=>operator+(int i1,int i2);
c1=a2+b2;//operator+(a2+b2);=>operator+(test t1,test t2);//這樣編不過
cout<<"c1="<<c1<<endl;
}
- C++運算符規(guī)定
- 重載運算符要保持原有運算符的意義
- 只能對已有運算符重載
- 重載的運算符不能改變原有的優(yōu)先級與結(jié)和性
- C++中參數(shù)說明都是內(nèi)部運算符時不能重載冗锁。//int operator+(int a,int b)不可實現(xiàn)
- 一個運算符還可以作為一個成員函數(shù)實現(xiàn)
- 作為成員的運算符
- 總結(jié)
- 操作符重載把操作符的作用擴展到對象類型
- 為了訪問被保護的對象,需要把重載函數(shù)定義成友元
- 操作符重載可以是成員函數(shù)
- 前增量后增量通過一個形參區(qū)分
#include <iostream>
using namespace std;
int a1=12,b1=13,c1;
class test
{
int m_z;
public:
test(int z)
{
m_z=z;
}
test()
{
m_z=10;
}
int getz()
{
return m_z;
}
void setz(int z)
{
m_z=z;
}
int operator+(test t2)
{
return m_z+t2.m_z;
}
friend test &operator++(test &t);//前綴++
friend test operator++(test &t,int);//后綴++
friend ostream &operator<<(ostream &c,test &z);
};
test a2(10),b2(5),c2;
test &operator++(test &t)//前綴++
{
++t.m_z;
return t;
}
test operator++(test &t,int)//后綴++
{
test z(t.m_z);
++t.m_z;
return z;
}
ostream &operator<<(ostream &c,test &z)
{
c<<z.m_z;
return c;
}
int main(int argc,char **argv)
{
c2=++a2;
cout<<"a2="<<a2.getz()<<endl;
cout<<"c2="<<c2.getz()<<endl;
cout<<a2<<endl;//operator<<(cout,a2);=>operator<<(ostream& ,test &);
}
- 操作符只能作為成員函數(shù)重載
- 重載總結(jié):
- 運算符重載必要性:增加可讀性
- 重載函數(shù)最好有相同類型
- 不要返回一個局部對象的引用
- 運算符作為成員函數(shù)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者