当我尝试使用访问我的静态变量时,Class.Variable
我得到了错误,Error left of 'Variable' must have class/struct/union
当我这样做时,我没有Class::Variable
得到任何错误。尽管在这两种情况下我都Variable
通过了智能感知。在这种情况下,.
和之间究竟有什么不同?::
问问题
379 次
6 回答
6
类的静态成员可以通过两种方式访问
(a) 使用类的实例 - 使用.
例如obj.variable
(b) 没有类的实例 - 使用::
例如class::variable
于 2011-07-18T10:34:13.120 回答
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;
于 2011-07-18T10:32:27.303 回答
0
is 用于类/命名空间范围,但在这种情况下,::
左侧.
必须是变量。请注意,这会起作用,这可能就是 Intellisense 也适合您的原因:
Class x;
doSomething( x.Variable );
于 2011-07-18T10:33:40.833 回答
0
Class::StaticProperty
InstanceOfClass.Property
于 2011-07-18T10:36:10.507 回答
0
.
是一个实例引用(例如,在 LHS 上有一个对象)。 ::
是静态引用。在 RHS 上有一个类型。
于 2011-07-18T10:31:35.757 回答
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。
于 2011-07-18T10:32:05.343 回答