C++面向对象友元函数运算符的重载
2018-01-01 17:33
405 查看
以课本复数类为例:
具体看代码,哪里不懂可以评论留言。
#include <iostream>
using namespace std;
class Complex{
public:
Complex(){real = 0,imag = 0;}
Complex(double r=0,double i=0):real(r),imag(i){}
void display();
friend Complex operator+(Complex,Complex);
Complex operator++();
Complex operator++(int);
// operator double(){return real;}
friend ostream& operator <<(ostream&,Complex&);
friend istream& operator >>(istream&,Complex&);
private:
double real,imag;
};
void Complex::display(){
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
Complex operator+(Complex c1,Complex c2){
return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
Complex Complex::operator++(){
real++;
imag++;
return *this;
}
Complex Complex::operator++(int){
real++;
imag++;
return *this;
}
ostream & operator <<(ostream &x,Complex &c){
x<<"("<<c.real<<","<<c.imag<<"i)";
return x;
}
istream & operator >>(istream&x,Complex &c){
x>>c.real>>c.imag;
return x;
}
int main(){
Complex c1(9,5),c2(1,1);
// cin>>c1>>c2;
c1.display();
c2.display();
(c1+c2).display();
++c2;
c2.display();
c1++;
(c1+c2).display();
Complex c = c1+c2;
cout<<c;
double d;
c = 2.5 + c1;
cout<<c<<endl;
c = c1+1.5;
cout<<c<<endl;
return 0;
}
具体看代码,哪里不懂可以评论留言。
#include <iostream>
using namespace std;
class Complex{
public:
Complex(){real = 0,imag = 0;}
Complex(double r=0,double i=0):real(r),imag(i){}
void display();
friend Complex operator+(Complex,Complex);
Complex operator++();
Complex operator++(int);
// operator double(){return real;}
friend ostream& operator <<(ostream&,Complex&);
friend istream& operator >>(istream&,Complex&);
private:
double real,imag;
};
void Complex::display(){
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
Complex operator+(Complex c1,Complex c2){
return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
Complex Complex::operator++(){
real++;
imag++;
return *this;
}
Complex Complex::operator++(int){
real++;
imag++;
return *this;
}
ostream & operator <<(ostream &x,Complex &c){
x<<"("<<c.real<<","<<c.imag<<"i)";
return x;
}
istream & operator >>(istream&x,Complex &c){
x>>c.real>>c.imag;
return x;
}
int main(){
Complex c1(9,5),c2(1,1);
// cin>>c1>>c2;
c1.display();
c2.display();
(c1+c2).display();
++c2;
c2.display();
c1++;
(c1+c2).display();
Complex c = c1+c2;
cout<<c;
double d;
c = 2.5 + c1;
cout<<c<<endl;
c = c1+1.5;
cout<<c<<endl;
return 0;
}
相关文章推荐
- 解析C++中不能重载为友元函数的四个运算符
- 解析C++中不能重载为友元函数的四个运算符
- 解析C++中不能重载为友元函数的四个运算符
- C++重载 箭头运算符
- C++中不能重载的运算符
- 【C++面向对象】函数操作符()的重载
- C++ 流运算符的重载
- c++重要知识点---模板、重载输入或输出运算符的运用
- c++内存泄露之重载new运算符
- 2013-4-19.2~用类的友元函数实现运算符的重载
- C++程序设计----- 运算符的重载 【项目3-分数类中的运算符重载】
- c++中不能重载的运算符
- C++友元函数让双目运算符更加人性化
- C++语言基础 例程 重载流插入运算符和流提取运算符
- C++不能重载的运算符
- C++中运算符的重载
- C++ 函数调用运算符 () 重载
- c++中不能重载的运算符
- C++中不能重载的运算符
- C++ 自定义string类 重载相关运算符