运算符重载中的范围运算符

Scope operator in Operator Overloading

本文关键字:运算符 范围 重载      更新时间:2023-10-16

我无法理解运算符重载中的范围运算符。有一些例子,当他们使用它时,当他们不使用它。当我应该写T::operator.我可以只写运算符仍然可以正常工作还是建议使用::?

示例:


原型示例(适用于 T 类( 内部类定义

T& T::operator +=(const T2& b){}

我可以这样写吗T& operator +=(const T2& b){}还是我应该一直这样写T& T::operator +=(const T2& b){}

运算符+=可以声明为类或类模板的成员函数或成员模板,并在类或类模板内或外部定义。

如果它是在类外部定义的,则需要 scope 运算符。

运算符也可以声明并定义为独立的非类函数

考虑以下演示程序

#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';
}    

在类中,不使用范围解析运算符::

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++代码。