zoukankan      html  css  js  c++  java
  • c++ operator重载的例子

    #include <iostream>
    using namespace std;
    class A
    {
    public:
    	A(double _data = 0.0):data(_data){}
    	A& operator = (const A& rhs)
    	{
    		data = rhs.data;
    		return *this;
    	}
    	
    	friend A operator + (const A& lhs,const A& rhs);
    	friend A operator - (const A& lhs,const A& rhs);
    	friend A operator * (const A& lhs,const A& rhs);
    	friend A operator + (const A& lhs,double rhs);
    	friend A operator + (double lhs,const A& rhs);
    	friend A operator * (const A& lhs,double rhs);
    	friend A operator * (double lhs,const A& rhs);
    	friend A operator - (const A& lhs,double rhs);
    	friend A operator - (double lhs,const A& rhs);
    	
    	
    	friend ostream& operator << (ostream& fout,A& a);
    //	A& operator += (const A& rhs);
    //	A& operator -= (const A& rhs);
    //	A& operator *= (const A& rhs);	
    private:
    	double data;
    };
    
    A operator + (const A& lhs,const A& rhs)
    {
    	A res(0);
    	res.data = lhs.data + rhs.data;
    	return res;
    }
    A operator - (const A& lhs,const A& rhs)
    {
    	A res(0);
    	res.data = lhs.data - rhs.data;
    	return res;
    }
    A operator * (const A& lhs,const A& rhs)
    {
    	A res(0);
    	res.data = lhs.data * rhs.data;
    	return res;
    }
     A operator + (const A& lhs,double rhs)
     {
     	A res(0);
    	res.data = lhs.data + rhs;
    	return res;
    }
    
    A operator + (double lhs,const A& rhs)
    {
     	A res(0);
    	res.data = lhs + rhs.data;
    	return res;
    }
    A operator * (const A& lhs,double rhs)
    {
    	A res(0);
    	res.data = lhs.data * rhs;
    	return res;
    }
    A operator * (double lhs,const A& rhs)
    {
    	A res(0);
    	res.data = lhs * rhs.data;
    	return res;
    }
    A operator - (const A& lhs,double rhs)
    {
    	A res(0);
    	res.data = lhs.data - rhs;
    	return res;	
    }
    A operator - (double lhs,const A& rhs)
    {
    	A res(0);
    	res.data = lhs - rhs.data;
    	return res;	
    }
    	
    ostream& operator << (ostream& fout,A& a)
    {
    	fout << a.data ;
    	return fout;
    }
    int main(int argc, char* argv[])
    {
    	A a(2.3);
    	A b(1.2);
    	A d(3.4);
    	A c;
    	c = a + b + d;
    	c=a+b;
    	c=a+1.0;
    	c=a-b;
    	c=a-1.0;
    	c=a*b;
    	c=a*1.0;
    	cout << c << endl;
    	
    	c=1.0+2.0*a*a-3.0*a*b;
    	cout << c << endl;
    	return 0;
    }
  • 相关阅读:
    WEB服务器3--IIS7.0安装和配置
    组件与组件之间的通信以及vue2.0中的变化、示例
    Vue2.0组件之间通信
    weex学习资源集合贴
    主题 : 好了,今天周六了,既然没人了,那么开讲多线程编程
    使用vue2.0 vue-router vuex 模拟ios7操作
    iOS开发之遍历Model类的属性并完善使用Runtime给Model类赋值
    iOS开发之使用Runtime给Model类赋值
    AFNetworking到底做了什么?
    webview300毫秒点击问题
  • 原文地址:https://www.cnblogs.com/speedmancs/p/2076873.html
Copyright © 2011-2022 走看看