我想知道C ++中的一些东西。
承认以下代码:
int bar;
class Foo
{
public:
Foo();
private:
int bar;
};
在我班上,两者之间有什么区别 this->bar
和 Foo::bar
?是否存在无效的情况?
我想知道C ++中的一些东西。
承认以下代码:
int bar;
class Foo
{
public:
Foo();
private:
int bar;
};
在我班上,两者之间有什么区别 this->bar
和 Foo::bar
?是否存在无效的情况?
课内 Foo
(具体而言)两者之间没有区别 bar
不是 static
。
Foo::bar
被称为成员的完全限定名称 bar
,这种形式在层次结构中可能有多个类型定义具有相同名称的成员的情况下非常有用。例如,你会的 需要 来写 Foo::bar
这里:
class Foo
{
public: Foo();
protected: int bar;
};
class Baz : public Foo
{
public: Baz();
protected: int bar;
void Test()
{
this->bar = 0; // Baz::bar
Foo::bar = 0; // the only way to refer to Foo::bar
}
};
他们做同样的事情成员。
但是,你无法使用 this->
区分类层次结构中的同名成员。你需要使用 ClassName::
版本来做到这一点。
对于我学习摆弄C / C ++的东西,使用 - > on something主要用于指针对象,而using ::用于作为命名空间或超类的一部分的类,它是一般的类。你包括在内
它还允许您引用具有相同名称的另一个类(大多数情况下是基类)的变量。对我来说,这个例子很明显,希望它对你有所帮助。
#include <iostream>
using std::cout;
using std::endl;
class Base {
public:
int bar;
Base() : bar(1){}
};
class Derived : public Base {
public:
int bar;
Derived() : Base(), bar(2) {}
void Test() {
cout << "#1: " << bar << endl; // 2
cout << "#2: " << this->bar << endl; // 2
cout << "#3: " << Base::bar << endl; // 1
cout << "#4: " << this->Base::bar << endl; // 1
cout << "#5: " << this->Derived::bar << endl; // 2
}
};
int main()
{
Derived test;
test.Test();
}
这是因为存储在类中的真实数据是这样的:
struct {
Base::bar = 1;
Derived::bar = 2; // The same as using bar
}