📜  范围解析运算符与C++中的该指针有关吗?

📅  最后修改于: 2021-05-25 21:39:35             🧑  作者: Mango

考虑下面的C++程序:

CPP
// C++ program to show that local parameters hide
// class members
#include 
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;
}


CPP
// C++ program to show use of this to access member when
// there is a local variable with same name.
#include 
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;
}


CPP
// C++ program to show that :: can be used to access static
// members when there is a local variable with same name
#include
using namespace std;
 
class Test
{
    static int a;  // a IS STATIC NOW
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;
}


输出
3

上面程序的输出为3,因为作为参数传递给“ func”的“ a”遮盖了类.ie 1的“ a”。
然后如何输出类的“ a”。这是该指针派上用场的地方。像“ cout << this-> a”这样的语句代替“ cout << a”可以简单地输出值1,因为该指针指向调用func的对象。

CPP

// C++ program to show use of this to access member when
// there is a local variable with same name.
#include 
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’,因为范围解析运算符只能用于静态数据成员(或类成员)。如果在上面的程序中使用范围解析运算符,则会得到编译器错误;如果在下面的程序中使用此指针,则也会得到编译器错误。

CPP

// C++ program to show that :: can be used to access static
// members when there is a local variable with same name
#include
using namespace std;
 
class Test
{
    static int a;  // a IS STATIC NOW
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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”