之间的区别。和::在C ++中为静态成员?

时间:2011-07-18 10:28:51

标签: c++ static scope-resolution

  

可能重复:
  When do I use a dot, arrow, or double colon to refer to members of a class in C++?

当我尝试使用Class.Variable访问我的静态变量时,我收到错误Error left of 'Variable' must have class/struct/union,当我Class::Variable时,我没有收到任何错误。虽然在这两种情况下我通过intellisense获得Variable。在这种情况下,.::之间究竟有什么不同?

6 个答案:

答案 0 :(得分:6)

可以通过两种方式访问​​类的静态成员

(a)使用课程实例 - 使用.例如obj.variable

(b)没有课程实例 - 使用::,例如class::variable

答案 1 :(得分:2)

.用于类名称的对象::

 struct foo {
     int x;
     static int y;
 };

 foo bar;

 bar.x = 10; // ok
 bar.y = 20; // ok - but bad practice

 foo.x = 10; // WRONG foo is class name
 foo.y = 20; // WRONG foo is class name

 foo::x = 10; // WRONG x requires object
 foo::y = 20; // ok

最佳做法:

 bar.x = 10; 
 foo::y = 20;

答案 2 :(得分:0)

.是一个实例引用(例如,在LHS上有一个对象)。 ::是静态参考。在RHS上有一种类型。

答案 3 :(得分:0)

点运算符,也称为“类成员访问运算符”,需要一个类/结构的实例。

struct X
{
    static int x = 5;
    int y = 3;
}
namespace NS
{
    int z = 1;
}

void foo()
{
    X instance;
    instance.x;  // OK, class member access operator
    X::x;        // OK, qualified id-expression
    instance.y;  // OK
    X::y;        // Not OK, y is not static, needs an instance.
    NS.z;        // Not OK: NS is not an object
    NS::z;       // OK, qualified-id expression for a namespace member.
}

措辞取自C ++ 0x FDIS。

答案 4 :(得分:0)

::用于类/命名空间范围,但在这种情况下,.的左侧必须是变量。请注意,这可能会有效,这可能就是为什么Intellisense适合您的原因:

Class x;
doSomething( x.Variable );

答案 5 :(得分:0)

Class::StaticProperty
InstanceOfClass.Property
相关问题