我想知道C++中的一些东西。this-> field和Class :: field之间的区别?
承认以下代码:
int bar;
class Foo
{
public:
Foo();
private:
int bar;
};
里面我的课,是有this->bar
和Foo::bar
之间有什么区别?有一种情况是无效的吗?
我想知道C++中的一些东西。this-> field和Class :: field之间的区别?
承认以下代码:
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
}
};
谢谢!我得到了它;) – 2013-04-27 22:14:59
对于我已经学会了用C/C++摆弄周围,使用 - >上的东西主要是为指针对象,并使用::用于那些命名空间或超类是部分类包括你的任何一般类别
我还没有看到其中的差别.. – 2013-04-27 22:11:57
那么,对于::它像使用std ::法院<<“”;使用::意味着你正在使用std命名空间的直接实现,而不是使用namespace std;在你的文件中。 - >就像是“指向”另一个对象的指针。这就是我看到他们使用的方式。 – user2277872 2013-04-27 22:22:35
它还允许你你用相同的名字引用(在大多数情况下,基类)其他类的变量。对我而言,从这个例子中可以看出,希望它能帮助你。
#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
}
当然,如果'bar'是一个虚函数,而不是一个数据成员,还有两者之间的差异。另外请注意,您可以像'this-> Foo :: bar'一样将它们组合起来。 – dyp 2013-04-27 22:21:44