首页 > 代码库 > 关于函数运算符号重载函数
关于函数运算符号重载函数
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; }
关于函数运算符号重载函数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。