为什么我不能重载 :: 运算符?

Why I cannot overload the :: operator?

我正在阅读 Stanley B. Lippman 的《C++ 入门》一书,在变量和基本类型部分我看到了作用域运算符 ::

我已经阅读了一些关于运算符重载的内容,我认为它在特殊情况下可能非常有用,但是当我在互联网上搜索时,我发现我根本无法重载 :: 运算符。

this post中我发现.运算符可以重载。但是,这可能会导致一个问题,即某个操作是针对对象重载 . 还是针对 . 引用的对象。

因此,我认为也许有一种方法可以重载 ::

但是如果不能,谁能解释一下为什么?

我对 :: 运算符的想法示例:

#include <iostream>

/*
 *For example:
 *I wanna increase 1 unit every time 
 *I call the global variable r doing ::r
 *insede of the main function
 */

int r = 42; 

int main()
{
    int r = 0;
    std::cout << ::r << " " << r << std::endl; //It would print 43 0 after the operator overload

    return 0;
}

不能重载 :: 的原因是标准禁止它。第 13.5.3 节有

The following operators cannot be overloaded:

. .* :: ?:

你不能超载它。

作用域 "operator" 与所有运算符不同,它在 运行 时什么都不做,它会影响编译时的名称查找,您无法更改它,因为它的工作只是告诉编译器在哪里可以找到名字。

这就是为什么你不能超载它。

例如:

#include <iostream>
#include <string>

std::string s = "Blah";

int main()
{
    std::string s = "World";
    ::s = "Hello ";

    std::cout << ::s << s << std::endl;

    return 0;
}

See on Coliru