我无法理解操作符重载中的范围操作符。当他们不使用它时,有一些例子。当我应该编写T::operator.时,我可以只编写操作符,还是建议使用::?
例子:
类定义中的原型示例(用于类T)
T& T::operator +=(const T2& b){}我能像T& operator +=(const T2& b){}一样写吗?还是应该总是像T& T::operator +=(const T2& b){}那样写?
发布于 2019-09-19 12:45:40
运算符+=可以声明为类或类模板的成员函数或成员模板,并在类或类模板内或外部定义。
如果它是在类之外定义的,那么就需要范围操作符。
运算符也可以声明并定义为独立的非类函数。
考虑下面的演示程序
#include <iostream>
struct A
{
int x = 0;
A & operator +=( char c )
{
x += c;
return *this;
}
};
struct B
{
int x = 0;
B & operator +=( char c );
};
B & B::operator +=( char c )
{
x += c;
return *this;
}
struct C
{
int x = 0;
};
C & operator +=( C & cls, char c )
{
cls.x += c;
return cls;
}
int main()
{
A a;
a += 'A';
std::cout << "a.x = " << a.x << '\n';
B b;
b += 'B';
std::cout << "b.x = " << b.x << '\n';
C c;
c += 'C';
std::cout << "c.x = " << c.x << '\n';
return 0;
}其输出是
a.x = 65
b.x = 66
c.x = 67还可以将运算符声明为模板运算符。例如
#include <iostream>
template <class T>
struct A
{
T x = T();
};
template <class T1, class T2>
T1 & operator +=( T1 &a, const T2 &x ) /* C++ 17 only requires requires( T1 t ) { t.x; }*/
{
a.x += x;
return a;
}
int main()
{
A<int> a;
std::cout << ( a += 10u ).x << '\n';
} 同样,如果运算符是成员函数模板,并且是在其类之外定义的,则需要范围解析操作符。
#include <iostream>
template <class T1>
struct A
{
T1 x = T1();
template <class T2>
A<T1> & operator +=( const T2 &x );
};
template <class T1>
template <class T2>
A<T1> & A<T1>::operator +=( const T2 &x )
{
this->x += x;
return *this;
}
int main()
{
A<int> a;
std::cout << ( a += 10u ).x << '\n';
} 发布于 2019-09-19 12:40:17
在类中,不使用范围解析操作符::
class T {
public:
// ...
T operator+=(const T2& b)
{
// ...
}
};如果在类之外定义运算符,则在类外定义中使用范围解析运算符::。你仍然在声明中漏掉了它:
class T {
public:
// ...
T operator+=(const T2& b);
};
// in the implementation
T T::operator+=(const T2& b)
{
// ...
}这与建议或良好做法无关。这里所述的一切都是唯一可以工作的方法,其他方法只是不正确的C++代码。
https://stackoverflow.com/questions/58010917
复制相似问题