Gab*_*iel 2 c++ operator-overloading c++11
我正在阅读Stanley B. Lippman的C++ Primer一书,在变量和基本类型部分,我看到了范围运算符::.
我已经阅读了一些关于运算符重载的内容,我认为它在特殊情况下非常有用,但是当我在互联网上搜索时,我发现我根本无法使::运算符超载.
在这篇文章中,我发现.操作员可能过载.但是,这可能导致关于操作是针对对象重载.还是针对所引用的对象的问题..
因此,我认为可能有一种方法可以超载::.
但如果它不能,任何人都可以解释我为什么?
我对::运算符的想法的一个例子:
#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;
}
Run Code Online (Sandbox Code Playgroud)
你不能超载它.
范围"运算符"不同于所有运算符在运行时不执行任何操作,它会影响编译时的名称查找,并且您无法更改它,因为它的工作只是告诉编译器在哪里查找名称.
这就是为什么你不能超载它.
例如:
#include <iostream>
#include <string>
std::string s = "Blah";
int main()
{
std::string s = "World";
::s = "Hello ";
std::cout << ::s << s << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你不能超载的原因::是标准禁止它.第13.5.3节有
以下运算符不能重载:
..*::?: