gpt4 book ai didi

c++ - 运算符重载中的作用域运算符

转载 作者:太空狗 更新时间:2023-10-29 20:49:33 25 4
gpt4 key购买 nike

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

例子:


原型(prototype)示例(针对 T 类)内部类定义

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

我可以这样写吗 T& operator +=(const T2& b){}或者我应该总是像 T& T::operator +=(const T2& b){}

这样写

最佳答案

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

如果它是在类外定义的,则需要作用域运算符。

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

考虑以下演示程序

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

关于c++ - 运算符重载中的作用域运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com