关于函数运算符号重载函数
Posted 于光远
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于函数运算符号重载函数相关的知识,希望对你有一定的参考价值。
class A{
public:
typedef int (*func)(int);
operator func();
};
int ff(int a){
return a;
}
A::operator func(){
return ff;
}
int main () {
cout<< A::func(9)<<endl;//运算符号 func() 这个func是typedef类型的。 调用的时候指定作用域
}
//运算符重载:成员函数方式 #include <iostream> using namespace std; class complex //复数类 { public: complex(){ real = imag = 0;} complex(double r, double i) { real = r; imag = i; } complex operator + (const complex &c); complex operator - (const complex &c); complex operator * (const complex &c); complex operator / (const complex &c); friend void print(const complex &c); //友元函数 private: double real; //实部 double imag; //虚部 }; inline complex complex::operator + (const complex &c) //定义为内联函数,代码复制,运算效率高 { return complex(real + c.real, imag + c.imag); } inline complex complex::operator - (const complex &c) { return complex(real - c.real, imag - c.imag); } inline complex complex::operator * (const complex &c) { return complex(real * c.real - imag * c.imag, real * c.real + imag * c.imag); } inline complex complex::operator / (const complex &c) { return complex( (real * c.real + imag * c. imag) / (c.real * c.real + c.imag * c.imag), (imag * c.real - real * c.imag) / (c.real * c.real + c.imag * c.imag) ); } void print(const complex &c) { if(c.imag < 0) cout<<c.real<<c.imag<<‘i‘<<endl; else cout<<c.real<<‘+‘<<c.imag<<‘i‘<<endl; } int main() { complex c1(2.0, 3.5), c2(6.7, 9.8), c3; c3 = c1 + c2; cout<<"c1 + c2 = "; print(c3); //友元函数不是成员函数,只能采用普通函数调用方式,不能通过类的对象调用 c3 = c1 - c2; cout<<"c1 - c2 = "; print(c3); c3 = c1 * c2; cout<<"c1 * c2 = "; print(c3); c3 = c1 / c2; cout<<"c1 / c2 = "; print(c3); return 0; }
以上是关于关于函数运算符号重载函数的主要内容,如果未能解决你的问题,请参考以下文章