C++ 重载运算符 运算符重载函数作为类成员函数 重载运算符+
2017-09-20 19:27
204 查看
用运算符重载函数作为类成员函数的方法重载运算符+
下面的例子来自于课本:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex() //无参构造函数
{
real = 0;
imag = 0;
}
Complex(double r, double i) //有参构造函数
{
real = r;
imag = i;
}
Complex operator + (Complex &c2); //声明重载运算符
void display(); //成员函数,对类中的变量进行输出
private:
double real;
double imag;
};
Complex Complex::operator +(Complex &c2)
{
Complex C;
C.real = real + c2.real;
C.imag = imag + c2.imag;
return C;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl; //输出复数形式
}
int main()
{
Complex c1(3,4), c2(5,-10), c3;
c3 = c1 + c2; //运算符+ 用于复数运算
cout<<"c1= ";
c1.display();
cout<<"c2= ";
c2.display();
cout<<"c1+c2= ";
c3.display();
return 0;
}
主函数中执行c1+c2语句,是调用了运算符重载函数operator +;
相当于c1.operator + ( );
运行结果为:
下面的例子来自于课本:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex() //无参构造函数
{
real = 0;
imag = 0;
}
Complex(double r, double i) //有参构造函数
{
real = r;
imag = i;
}
Complex operator + (Complex &c2); //声明重载运算符
void display(); //成员函数,对类中的变量进行输出
private:
double real;
double imag;
};
Complex Complex::operator +(Complex &c2)
{
Complex C;
C.real = real + c2.real;
C.imag = imag + c2.imag;
return C;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl; //输出复数形式
}
int main()
{
Complex c1(3,4), c2(5,-10), c3;
c3 = c1 + c2; //运算符+ 用于复数运算
cout<<"c1= ";
c1.display();
cout<<"c2= ";
c2.display();
cout<<"c1+c2= ";
c3.display();
return 0;
}
主函数中执行c1+c2语句,是调用了运算符重载函数operator +;
相当于c1.operator + ( );
运行结果为:
相关文章推荐
- C++学习之路—运算符重载(二)运算符重载作为类的成员函数和友元函数
- C++四个默认成员函数&运算符重载
- C++中类成员函数作为回调函数
- C++成员函数作为回调函数的问题
- 《C++第八周实验报告1-1(1)》---复数类中的运算符重载用类的成员函数完成
- 运算符重载函数作为类成员函数和友元函数
- C++中类的成员函数作为 pthread_create的线程函数
- C++将类的成员函数作为回调函数
- 在C++的类中使用类成员函数作为回调函数
- C++中类成员函数作为回调函数 [转]
- C++中类成员函数作为回调函数
- C++静态成员函数,静态成员变量,运算符重载
- C++的成员函数作为回调函数
- 【C++】类和对象--基础知识+四个默认成员函数+运算符重载
- C++中类成员函数作为回调函数
- c++ 运算符重载之成员函数重载
- C++ 实现把非静态成员函数作为回调函数(非static)
- C++ 实现把非静态成员函数作为回调函数(非static)(转 待研究)
- 从零开始学C++之运算符重载(一):以成员函数方式重载、以友元函数方式重载
- 将类成员函数作为线程入口函数——关于C++ 类静态成员的学习