0
当声明和使用静态const积分时,我发现使用我正在使用的对象引用来访问变量是方便和自然的,而不是用类名完全限定它。我想知道这是否有缺点?举个例子:通过指针/引用C++静态常量积分变量的用法?
class MyLongClassNameIdRatherNotHaveEverywhere {
public:
static const int Len = 6;
//...
void otherInterestingThings();
void someWorkToDo();
};
int main() {
MyLongClassNameIdRatherNotHaveEverywhere *lcn = new MyLongClassNameIdRatherNotHaveEverywhere;
lcn->someWorkToDo();
cout << "the length is: " << lcn->Len << endl;
delete lcn;
return 0;
}
通知的lcn->Len
......这真是一个恒定的,而事实上,如果lcn
都为空的,lcn->Len
仍然编译和运行就好了。我可以在那里写出MyLongClassNameIdRatherNotHaveEverywhere::Len
,这当然会让它更明显(至少对我来说)这是一个常数。还有其他缺点吗?
*“事实上,如果lcn为空,这仍然编译并运行得很好”*这并不合法。这是不确定的行为。 – jrok
@jrok:不,它不是。您不访问对象,只是使用对象类型来访问类的静态成员。指针是* not * dereferenced,并且没有未定义的行为。 –
@DavidRodríguez-dribeas我们的意思是一样的吗?我的意思是'X * lcn = nullptr; lcn-> foo;'那种事。 – jrok