范围解析运算符 用于访问静态或类成员,以及 this指针 用于在存在同名局部变量时访问对象成员。
null
考虑下面的C++程序:
CPP
// C++ program to show that local parameters hide // class members #include <iostream> using namespace std; class Test { int a; public : Test() { a = 1; } // Local parameter 'a' hides class member 'a' void func( int a) { cout << a; } }; // Driver Code int main() { Test obj; int k = 3; obj.func(k); return 0; } |
输出
3
说明: 上述程序的输出为 3. 因为“a”作为一个参数传递给 func 阴影笼罩着班级的“a”。i、 e 1
然后如何输出类的“a”。这就是 this指针 很方便。像这样的声明 不能 而不是 不能 当指针指向对象时,可以简单地输出值1 func 被称为。
CPP
// C++ program to show use of this to access member when // there is a local variable with same name #include <iostream> using namespace std; class Test { int a; public : Test() { a = 1; } // Local parameter 'a' hides object's member // 'a', but we can access it using this. void func( int a) { cout << this ->a; } }; // Driver code int main() { Test obj; int k = 3; obj.func(k); return 0; } |
输出
1
怎么样 范围解析运算符 ?
在上面的示例中,我们不能使用范围解析运算符打印对象的成员“a”,因为范围解析运算符只能用于静态数据成员(或类成员)。如果我们在上面的程序中使用scope resolution操作符,我们会得到一个编译器错误,如果我们在下面的程序中使用这个指针,那么我们也会得到一个编译器错误。
CPP
// C++ program to show that scope resolution operator can be // used to access static members when there is a local // variable with same name #include <iostream> using namespace std; class Test { static int a; public : // Local parameter 'a' hides class member // 'a', but we can access it using :: void func( int a) { cout << Test::a; } }; // In C++, static members must be explicitly defined // like this int Test::a = 1; // Driver code int main() { Test obj; int k = 3; obj.func(k); return 0; } |
输出
1
本文由 阿卡什·萨赫德瓦 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以写一篇文章,然后将文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END