C++重载操作符笔记

重载和多态是不一样的,重载主要作用是多操作符号的重载。(Operator overloading)

如有下面的类:

class complex { // very simplified complex
double re, im;
public:
complex(double r, double i) :re{r}, im{i} { }
complex operator+(complex);
complex operator*(complex);
};


要实现其中的+和*操作,就必须自定义其函数功能,也就是重载了编译器原有的+和*操作。

void f(complex a, complex b)
{
complex c = a + b; // shor thand
complex d = a.operator+(b); // explicit call
}


下面操作符都是可以重载的:

注意其重载的参数不能出错:

class X {
public: // members (with implicit this pointer):
X∗ operator&(); // prefix unary & (address of)
X operator&(X); // binar y & (and)
X operator++(int); // postfix increment (see §19.2.4)
X operator&(X,X); // error : ter nary
X operator/(); // error : unar y /
};
X operator−(X); //prefix unary minus
X operator−(X,X); //binar y minus
X operator−−(X&,int); // postfix decrement
X operator−(); //error : no operand
X operator−(X,X,X); // error : ter nary
X operator%(X); // error : unar y %

操作符= (assignment), & (address-of), and , (sequencing) 都有预先定义的意义,但是可以利用deleted关键字去掉:

class X {
public:
// ...
void operator=(const X&) = delete;
void operator&() = delete;
void operator,(const X&) = delete;
// ...
};
void f(X a, X b)
{
a = b; // error : no operator=()
&a; // error : no operator&()
a,b; // error : no operator,()
}

操作符的重载参数必须有一个是用户自定义的数据类型,这样就保证了不可以修改原有操作符的作用。

日期数据类型重载++:

enum Day { sun, mon, tue, wed, thu, fri, sat };
Day& operator++(Day& d)
{
return d = (sat==d) ? sun : static_cast<Day>(d+1);
}


如果是自定义的类,成员多,占内存大,那么就定义move operation会让传输速度加快。

Matrix operator+(const Matrix& a, const Matrix& b) // return-by-value
{
Matrix res {a};
return res+=b;
}

操作符如果是返回参数的其中一个对象的就通常是返回引用参数:

Matrix& Matrix::operator+=(const Matrix& a) // return-by-reference
{
if (dim[0]!=a.dim[0] || dim[1]!=a.dim[1])
throw std::exception("bad Matrix += argument");
double∗ p = elem;
double∗ q = a.elem;
double∗ end = p+dim[0]∗dim[1];
while(p!=end)
∗p++ += ∗q++
return ∗this;
}

单操作符!例子。

X operator!(X);
struct Z {
Z operator!(); //does not hide ::operator!()
X f(X x) { /* ... */ return !x; } // invoke ::operator!(X)
int f(int x) { /* ... */ return !x; } // invoke the built-in ! for ints
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值