c++ 操作符重載
/* file = main.cpp 涉及操作符重載,友元函數,重載類型轉換*/
#include <iostream>
#include "testClass.h"
using namespace std;
int main()
{
testClass tc1(2);
testClass tc2(3);
testClass tc3 = 1 + tc1 + tc2 + 4;// 重載加法
testClass tc4 = 5 - tc2 - tc1 - 1;// 重載減法
int a = tc1;// 重載了類型轉換
cout << "tc3:= " << tc3 << ", tc4:=" << tc4 << endl;
// 重載了類型轉換才能用下面這樣的語句
cout << "tc3 + t4 := " << tc3 + tc4 << endl;
cout << "tc3 - t4 := " << tc3 - tc4 << endl;
return 0;
}
/* file = testClass.h */
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <iostream>
class testClass
{
public:
testClass(int i);
virtual ~testClass();
testClass operator +(testClass & sf) const;
testClass operator +(int j) const;
testClass operator -(testClass & sf) const;
testClass operator -(int j) const;
operator int() const;// 重載類型轉換;必須是成員函數,零參數,無傳回值
friend testClass operator +(int j, testClass & sf);
friend testClass operator -(int j, testClass & sf);
friend std::ostream & operator <<(std::ostream & os, testClass & sf);
protected:
private:
int m_i;
};
#endif // TESTCLASS_H
/* file = testClass.cpp */
#include "testClass.h"
testClass::testClass(int i)
{
this->m_i = i;
}
testClass::~testClass()
{
}
testClass testClass::operator +(testClass & sf) const{
testClass tc(this->m_i + sf.m_i);
return tc;
}
testClass testClass::operator +(int j) const{
testClass tc(this->m_i + j);
return tc;
}
testClass operator +(int j, testClass & sf){
return sf + j;
}
testClass testClass::operator -(testClass & sf) const{
testClass tc(this->m_i - sf.m_i);
return tc;
}
testClass testClass::operator -(int j) const{
testClass tc(this->m_i - j);
return tc;
}
testClass operator -(int j, testClass & sf){
testClass tc(j - sf.m_i);
return tc;
}
testClass::operator int() const{
return this->m_i;
}
std::ostream & operator <<(std::ostream & os, testClass & sf){
os << sf.m_i;
return os;
}
共含三個檔案,在winxp + codeblock 8.02 上測試通過,由於codeblock 新建立的類檔案標頭檔放在include路徑下,需要在project -> build options -> Search directories -> Compiler -> Add , 添加一個include 路徑,否則codeblock 會報告找不到標頭檔"testClass.h"