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

C++运算符重载(1) - 介绍

2015-05-26 01:18 295 查看

1.运行符重载

C++中,可以在定义的类中使用操作符。例如,可以对于一个String类,重载操作符+,这样就可以在两个string之间直接使用+。

一个简单的例子:

#include<iostream>
using namespace std;

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0)  {real = r;   imag = i;}

//两个复数相加时,此函数会被调用
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // 调用"operator+"的例子
c3.print();
}
输出:

12 + i9

2.运算符函数与普通函数的区别

运算符函数与普通函数一样。唯一的不同在于,运算符函数的名字通常由operator关键字加上运算操作符组成。当相关的操作符被使用时,则重载的操作符函数会被调用。

下面是一个全局运算符函数的例子:

#include<iostream>
using namespace std;

class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)  {real = r;   imag = i;}
void print() { cout << real << " + i" << imag << endl; }

// 将全局的重载运算符函数,做为类的友元函数,这样可以访问私有数据
friend Complex operator + (Complex const &, Complex const &);
};

Complex operator + (Complex const &c1, Complex const &c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // 调用"operator+"
c3.print();
return 0;
}

3.不能被重载的运算符

除了少数的运算符,绝大部分都能被重载。下面是不能被重载的操作符列表:

.
::
?:
sizeof
为何上面4种操作符不能重载?

可以参考 http://www.stroustrup.com/bs_faq2.html#overload-dot

4.关于运算符操作的重要信息:

1) 为了让操作符重载能工作,至少得有一个操作对象是用户自定义的类对象。

2) 赋值操作符: 编译器会自动的给每个类创建一个默认的赋值操作符。它会将所有成员从右边赋给左边,大多数情况下可以正常工作(不正常的地方与拷贝构造一样)。

3) 转换操作符: 我们可以自定义转换操作符,用来将一个类型转换成另外类型。

#include <iostream>
using namespace std;
class Fraction
{
int num, den;
public:
Fraction(int n,  int d) { num = n; den = d; }

// 转换操作符:返回float值的分数
operator float() const {
return float(num) / float(den);
}
};

int main() {
Fraction f(2, 5);
float val = f;
cout << val;
return 0;
}
输出:

0.4

转换操作符必须是一个成员方法。 其它的操作符可以是成员方法或者全局方法。

4) 任何只带有一个参数的构造函数,都可以当做转换构造函数使用,意味着可以用于隐式转换。

#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int i = 0, int j = 0) {
x = i;   y = j;
}
void print() {
cout << endl << " x = " << x << ", y = " << y;
}
};

int main() {
Point t(20, 20);
t.show();
t = 30;   // t的x成员会变成30
t.print();
return 0;
}
输出:

x = 20, y = 20

x = 30, y = 0

本系列的后续文章会,会讨论一些重要操作符的重载,例如 new, delete, comma, function call, arrow, 等.

更多参考:
http://en.wikipedia.org/wiki/Operator_overloading
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: