class TStrOp { private: string value; public: TStrOp():value("0") { } TStrOp(string arg):value(arg) { } long GetValue() { return atol (value.c_str()); } friend long operator + (TStrOp a, TStrOp b); friend long operator - (TStrOp a, TStrOp b); };
int main() { TStrOp a("1234"); TStrOp b("4321");
cout << "Value of a == " << a.GetValue() << endl; cout << "Value of b == " << b.GetValue() << endl; cout << "a + b + 6 == " << (a + b + 6) << endl; cout << "a - b + 10 == " << (a - b + 10) << endl;
return 0; }
//由于函数是朋友无需加类名(非类TStrOp的成员函数) //在不访问私有数据情况下不用设为友元函数 long operator + (TStrOp a, TStrOp b) { return ( atol(a.value.c_str()) + atol(b.value.c_str()) ); }
long operator- (TStrOp a, TStrOp b) { return ( atol(a.value.c_str()) - atol(b.value.c_str()) ); }
class TStrOp { private: string value; public: TStrOp():value("0") { } TStrOp(string arg):value(arg) { } long GetValue() { return atol (value.c_str()); } long operator + (TStrOp b); long operator - (TStrOp b); };
int main() { TStrOp a("1234"); TStrOp b("4321");
cout << "Value of a == " << a.GetValue() << endl; cout << "Value of b == " << b.GetValue() << endl; cout << "a + b + 6 == " << (a + b + 6) << endl; cout << "a - b + 10 == " << (a - b + 10) << endl;
return 0; }
//重载类TStrOp 的成员函数 //重载的操作符函数已经是类的成员,可以访问 //保护成员,并接收隐藏的this指针,该指针指向 //调用其函数的对象,因此只需一个参数。但它 //们仍然是二元操作符,因为仍然接收两个参数 long TStrOp::operator + ( TStrOp b) { return ( atol(value.c_str()) + atol(b.value.c_str()) ); }
long TStrOp::operator- (TStrOp b) { return ( atol(value.c_str()) - atol(b.value.c_str()) ); }
class TStrOp{ private: string value; public: TStrOp():value("0") { } TStrOp(string arg):value(arg) { } long GetValue() { return (long)(* this); } long operator + (TStrOp b); long operator - (TStrOp b); long operator - (); operator long () { return atol(value.c_str()); } //重载long型转换符,可换成其它类型 };
int main() {
TStrOp a("1234"); TStrOp b("4321");
cout << "Value of a == " << a.GetValue() << endl; cout << "Value of b == " << b.GetValue() << endl; cout << "a + b + 6 == " << (a + b + 6) << endl; cout << "a - b + 10 == " << (a - b + 10) << endl;
TStrOp myvalue("9876"); long x = myvalue; cout << "x + b - 9 == " << (x + b - 9) << endl;
return 0; }
long TStrOp::operator + (TStrOp b) { return (long)*this + (long)b; //内部调用类型重载操作符,强制转换 }
long TStrOp::operator -(TStrOp b) { return (long)*this - (long)b; }
long TStrOp::operator -() { return - (long)(*this); }
重载操作符一些定义: int operator ++() { return ++x; } //prefix ++ int operator ++(int) { return x++; } //postfix ++ int operator --() { return --x; } //prefix --
int operator --(int) { return x--; } //postfix --
class TError { }; class PseudoArray { private: int value0; int value1; int value2; int value3; public: PseudoArray(int v0, int v1, int v2, int v3): value0(v0), value1(v1), value2(v2), value3(v3) { } int &operator[](unsigned i) throw (TError); };