运算符重载中的范围运算符
Scope operator in Operator Overloading
我无法理解运算符重载中的范围运算符。有一些例子,当他们使用它时,当他们不使用它。当我应该写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++代码。
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- ::(范围解析运算符)前面没有任何东西
- 使用范围解析运算符时,在构造函数中调用虚拟方法是否安全?
- 迭代器的范围 TS 和 C++20 概念是否需要能够使用"运算符>"?
- 运算符重载中的范围运算符
- 重载运算符 [] 以接受范围
- 为什么按位运算符在使用与整数中提供的位数相同的位数计算可能的最大范围时会产生错误
- 为什么C++找不到布尔运算符,当有一个!范围内的运算符?
- 运算符>的范围
- 范围分辨率运算符在类型:: var的情况下返回什么
- 如何在C 中访问无范围分辨率运算符的标头构件类型
- 为什么我们要把 :: (范围重新定位运算符)放在迭代器之前
- 删除复制构造函数和运算符=类范围访问
- 为什么可以使用范围运算符和类 A 名称在类 B 中访问类 A(公共)中的枚举
- 友元运算符中的变量范围
- C++是否提供了一种在没有范围解析运算符的情况下访问类中的类的方法?
- 范围分辨率运算符被两次使用
- 基于范围的循环使用另一个运算符
- 关于在 STL 中使用范围解析运算符的困惑
- 为什么范围解析运算符在类外给出错误