为什么在 c++ 中重载运算符时不需要范围解析 (::)?
Why isn't the scope resolution (::) needed when overloading operators in c++?
通常,当您在类声明中声明一个方法并在外部定义它时,您需要指定其作用域。
由于我读到运算符几乎是常规方法,因此我发现很难理解以下行为:
class A
{
public:
A(int x)
{ this->x = x;}
int foo();
friend const A operator+ (const A& left,const int right);
private:
int x;
};
const A operator+ (const A& left,const int right) //can't be A::operator+
{
return A(left.x + right);
}
int A::foo() // A:: is needed here
{
return 5;
}
int main(int argc, char **argv) {
A a(1);
a = a + 4;
a.operator =(a+5);
a.foo();
}
为什么我们不需要指定我们要定义\重载的"运算符+"?是从操作数推断出来的吗?
因为operator+
是一个自由函数,与A
类完全无关。碰巧它的一个参数是类A
.
这意味着它与A::operator+
定义为:
class A {
public:
const A operator+(const int);
};
在代码示例中,您将为类定义一个friend
函数。因此,free 函数现在可以访问类的私有和受保护部分。如果你不定义它(operator+
),friend
只能访问A
的公共成员。这就是为什么你要让它friend
.
这是因为在这种情况下,运算符+不是类A的成员,而是一个友好的函数。
在您的情况下,运算符 + 不是类 A 的成员。这通常是定义二元运算符的正确方法,以便运算符可以与左侧的文本一起使用。
但是,大多数运算符被定义为类范围内的普通类成员。EG,
A& A::operator=(A rhs)
{
swap(rhs);
return *this;
}
这是一个更完整的答案:运算符重载
相关文章:
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 为什么output_editor Concept不需要output_e迭代器标记
- 在除法中不需要四舍五入
- 与C代码相比,为什么C++代码不需要"#define _POSIX_C_SOURCE 200809L"?
- 将值从另一个数组写入数组,不包括不需要的值 C++
- C++ 写入路径名中包含不需要的空字符的文件
- 是否有必要获取锁并在不需要唤醒线程时通知condition_variable?
- 使用 assimp 加载模型 - 不需要提升?
- 为什么转换函数声明不需要至少一个定义类型说明符
- 返回不需要的值的二叉搜索程序
- 当我不需要数据库中的所有值时,如何部分初始化 c++ 对象?
- C++:用户输入会产生不需要的行为
- 如何在不需要LIBCD.lib的情况下在Visual Studio 6中编译C项目
- 为什么python需要全局关键字而C/C++不需要?
- 将一个宏传递到另一个宏而不是直接传递内容时会出现不需要的额外"空"参数
- 为什么我们需要在 C++ 中检查空指针,而在 Java 中不需要?
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- 范围运算符需要查找 std 命名空间而不是提升
- 为什么在 c++ 中重载运算符时不需要范围解析 (::)?