范围解析运算符与 C++ 中的 this 指针
范围解析运算符用于访问静态或类成员,此指针用于在存在同名的局部变量时访问对象成员。
考虑下面的 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 scope resolution operator 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;
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”遮盖了类的“a”,即 1
那么如何输出类的'a'。这就是这个指针派上用场的地方。像cout <
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 scope resolution operator 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;
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