dee*_*iip 0 c++ return reference
说我上课了
class A{
A& operator+ (size_t ofst)
{
//some calculation
//return
}
};
Run Code Online (Sandbox Code Playgroud)
在这里,我不能写
return this;
Run Code Online (Sandbox Code Playgroud)
因为A*无法转换为A&.那么如何实现这个呢?我想返回引用而不是指针.
作为类比,有一个流类的>>或<<运算符.据我所知,这两个返回对自身的引用.标准库如何实现这一目标?
写*this.
一元运算*符执行解除引用.所以,你从指针开始this,并应用于*获取它指向的东西,即实际的底层对象.
结果*this实际上不是一个引用,而是一个左值,然后很高兴地绑定到引用,它是函数/运算符的返回值.
至于流如何做,流的大多数运算符重载都是非成员:
std::ostream& operator<<(std::ostream& os, const MyType& obj)
{
os << obj.someStringRepresentationIGuess();
return os;
}
Run Code Online (Sandbox Code Playgroud)
那些不会返回的人*this:
std::ostream& std::ostream::operator<<(int x)
{
doSomethingToAddIntToBuffer(x);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
这通常不适用于运营商+,但它会+=:
class A
{
A operator+(size_t ofst)
{
A tmp = *this;
tmp += ofst;
return tmp;
}
A& operator+=(size_t ofst)
{
// some calculation
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
这是因为约定+适用于新对象; 否则,以下代码的结果将完全令人惊讶:
int x = 5;
int y = x + 2;
// is y 5 or 7?
// is x 5 or 7?
Run Code Online (Sandbox Code Playgroud)