C++运算符重载(operator)

C++不允许用户自己定义新的运算符,只能对已有的运算符进行重载.

运算符重载:

有5个运算符不允许重载:

1.  . (成员访问运算符).

2. .* (成员指针访问运算符).

3. ::(域运算符).

4. sizeof(尺寸运算符).

5. ?: (条件运算符).

重载时需注意:

1. 不能改变运算符对象的操作个数.

2. 不能改变运算符的优先级别.

3. 不能改变运算符的结合性.

4. 重载运算符的函数不能有默认参数.

5. 重载运算符必须和用户定义的自定义类型的对象一起使用.其参数至少有一个是类对象或类对象的引用.(也就是说.参数不能全部是C++的标准类型.

这样约定是为了防止用户修改用于标准类型结构的运算符性质).

运算符重载格式:

函数类型 operator 运算符名称 (形参列表) {

对运算符的重载处理;

}


例子:
#include <iostream>
using namespace std;

class Complex {
public :
	Complex();
	Complex(int r, int i);
	Complex operator+(Complex &d);	//重载+法运算符.
	void print();

private:
	int i;
	int r;
};

Complex::Complex() {
	this->i = 0;
	this->r = 0;
}

Complex::Complex(int i, int r) {
	this->i = i;
	this->r = r;
}

//重载+号.实现两数相加.
Complex Complex::operator+(Complex &d) {
	Complex c;
	c.i = this->i + d.i;
	c.r = this->r + d.r;

	return c;
}

void Complex::print(){
	cout<<"("<<i<<","<<r<<")"<<endl;
}

void main(){
	Complex c1(3,4), c2(5,6), c3;
	c3 = c1 + c2;   //这句话类似于:c3 = c1.operator+(c2);
	cout<<"c1=";
	c1.print();

	cout<<"c2=";
	c2.print();

	cout<<"c3=";
	c3.print();
}	

简单例子:
#include <iostream>

using namespace std;

struct Complex
{
    float real;
    float image;

};

Complex operator + (Complex a, Complex b)
{
    Complex c;
    c.real = a.real + b.real;
    c.image = a.image + b.image;
    return c;
};

int main(int argc, char *argv[])
{

    Complex aa = { 1, 2}, bb = { 2, 3};
    Complex cc = operator+(aa, bb);
    cout << cc.real << " " << cc.image << endl;
    cout << "Run End!" << endl;
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值