您的位置:首页 > 编程语言 > C语言/C++

C++面向对象程序设计的一些知识点(5)

2013-11-19 20:19 190 查看
摘要:运算符能给程序员提供一种书写数学公式的感觉,本质上运算符也是一种函数,因此有类内部运算符和全局运算符之分,通过重载,运算符的“动作”更加有针对性,编写代码更像写英文文章。

1、C++标准允许将运算符重载为类成员或者全局的,一般如果是全局的话,为了效率,都是把它们定义为类友元函数。

/*
** 类型转换运算符重载,从内置类型到对象
*/
#include <iostream>

using namespace std;

class Complex
{
public:
Complex(double real, double image)
{
this->real = real;
this->image = image;
}
Complex(const Complex &c)
{
real = c.real;
image = c.image;
cout << "copy constructor called..." << endl;
}
Complex(double real)
{
this->real = real;
this->image = 0;
cout << "one parameter called..." << endl;
}
~Complex()
{}
public:
Complex& operator+=(const Complex &c)
{
real += c.real;
image += c.image;
cout << "overload operator+= called..." << endl;
return *this;
}
void show()
{
cout << real;
if(image >= 0)
cout << "+" << image << "i" << endl;
else
cout << image << "i" << endl;
}
private:
double real;
double image;
};

int main()
{
Complex c1(0, 1.1);
c1 += 3.3;
c1.show();

int i;
cin >> i;
return 0;
}


类型转换-从内置类型到对象
5、运算符重载规则

运算符规则
所有单目运算符建议重载为非static成员函数
=、()、[]、->、*建议重载为非static成员函数
+=、-=、/=、*=、&=、|=、~=、%=、>>=、<<=建议重载为非static成员函数
所有其他运算符建议重载为全局函数或类的友元函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: