为什么 C++允许变量名和类名相同吗?
#include <iostream>
#include <vector>
using namespace std;
typedef int UINT4;
class Hack
{};
Hack& operator <(Hack& a , Hack& b)
{
std::cerr << "1";
return a;
}
Hack& operator >(Hack& a, Hack& b)
{
std::cerr << "2";
return a;
}
int main()
{
Hack vector; // It SHOULD be OK!?
Hack UINT4; // It SHOULD be OK!?
Hack v;
Hack Hack; // It SHOULD be OK!?
Hack = v; // It SHOULD be OK!?
// Please stop to think for a moment: What will the following output?
vector<UINT4> v;
// Oh, my god! The whole world goes mad!
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
typedef int UINT4;
class Hack
{};
Hack& operator <(Hack& a , Hack& b)
{
std::cerr << "1";
return a;
}
Hack& operator >(Hack& a, Hack& b)
{
std::cerr << "2";
return a;
}
int main()
{
Hack vector; // It SHOULD be OK!?
Hack UINT4; // It SHOULD be OK!?
Hack v;
Hack Hack; // It SHOULD be OK!?
Hack = v; // It SHOULD be OK!?
// Please stop to think for a moment: What will the following output?
vector<UINT4> v;
// Oh, my god! The whole world goes mad!
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听说过以下内容吗?请仔细查看参数类型:)
您在问题中所显示的内容实际上并不太引人注目。您在局部范围内声明变量名称,但程序中的类型名称位于全局范围内。我现在就给你看一些真正变态的东西:
W00t?为什么C++允许我们创建两个同名的变量!?!
好吧,我是开玩笑的。现在,我将向您介绍重复名称的真正黑暗面。考虑一下 C++ 给我们带来了什么!
本质上,这个都是为了 C 兼容性:)
Ever heard of the following? Please look close at the parameter types :)
What you have shown in your question really isn't too dramatic. You declare a variable name in a local scope, but the type names in your program are in global scope. I will show you some real pervert thing now:
W00t? Why does C++ allow us to create two variables of the same name!?!
Alright, I was kidding. I will now introduce you into the real dark sides of messing with duplicate names. Consider what C++ allows us!
In essence, this one is all for C compatibility :)
您是从一个非常知道他正在使用类名作为变量标识符的人的角度提出问题:显然,这不是最佳实践。
现在,让我们换个角度来看:假设您不知道您所包含的一些不起眼的头文件中有一个奇怪的
typedef int i;
。您希望它能够破坏以下无辜的代码吗?You're asking the question from the point of view or someone who very well knows that he is using a class name as a variable identifier : obviously, this isn't a best practice.
Now, let's take it the other way around : suppose you have no idea that there is a weird
typedef int i;
in some obscure header file you are including. Would you expect it to break the following innocent code ?