使用友元函数形式进行运算符重载
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用友元函数形式进行运算符重载相关的知识,希望对你有一定的参考价值。
#include <iostream> using namespace std; class Complex { private: int real; int image; public: Complex(int real=0,int image=0):real(real),image(image) { cout<<"Complex::Complex():"<<this<<endl; } Complex(const Complex &x):real(x.real),image(x.image) { cout<<"Complex::Complex(Complex &):"<<this<<endl; } ~Complex() { cout<<"Complex::~Complex():"<<this<<endl; } friend Complex operator+(Complex &a,Complex &b); friend Complex operator-(Complex &a,Complex &b); void show(); }; Complex operator+(Complex &a,Complex &b) { return Complex(a.real+b.real,a.image+b.image); } Complex operator-(Complex &a,Complex &b) { return Complex(a.real-b.real,a.image-b.image); } void Complex::show() { cout<<real; if(image>0) cout<<"+"; cout<<image<<"i"<<endl; } int main(int argc, char *argv[]) { Complex a(10,20); Complex b(70,80); Complex c=a+b; Complex d=a-b; a.show(); b.show(); c.show(); d.show(); return 0; }
本文出自 “10628473” 博客,请务必保留此出处http://10638473.blog.51cto.com/10628473/1964406
以上是关于使用友元函数形式进行运算符重载的主要内容,如果未能解决你的问题,请参考以下文章