$(document).ready(function() { // 禁止右键 $(document).bind("contextmenu", function(){return false;}); // 禁止选择 $(document).bind("selectstart", function(){return false;}); // 禁止Ctrl+C 和Ctrl+A });

C++,当类名和对象名称相同时会发生什么?

今天突发奇想,如果类名和由这个类声明的对象标识符相同时会发生什么,然后就测试了一下。如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
class a
{
public:
a() {cout << "a~~~~~" << endl;}
};
int main(void)
{
    a a;
     
    return 0;
}

  正常编译通过,运行结果也是正常的。仔细想想这种结果也是意料之中的,因为在main函数体中刚开始的时候遇到第一个a,由于main局部域没有a的声明,所以继续向外面的全局域寻找,接着找到a的声明,并解析a是一个类,之后遇到第二个a,这时这个a成了一个类型为a的对象,此声明后局部域中的a已经隐藏了全局域中的a,如若继续写a b;肯定会报错,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
class a
{
public:
a() {cout << "a~~~~~" << endl;}
};
int main(void)
{
    a a;
    a b;
 
    return 0;
}

  这次是肯定无法编译通过的。如果再想访问全局的那个a只能用域操作符了(::a),如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
class a
{
public:
a() {cout << "a~~~~~" << endl;}
};
int main(void)
{
    a a;
    //a b;
    ::a b;
    return 0;
}

原文链接:https://www.cnblogs.com/xxNote/p/4183328.html

posted on 2022-04-02 11:12  是晓雨呀  阅读(129)  评论(0编辑  收藏  举报

导航