开发者

Why does C++ prohibit non-integral data member initialization at the point of definition?

class Interface {
public: 
  static const int i = 1;
  static const double d = 1.0;
    //! static const string *name = new string("Interface 开发者_JS百科name");
    virtual string getName() = 0;
}

Since C++ is a traditional truely compiled programming language,it could be easily convinced that it does allow object initialization(?).But why do C++ prohibit double initialization at the point of defintion?I see that g++ now support double initialization at the point of definition,but not msvc.

My question is,since it's easy to support primitive types - float/double initialization at the point of definition and it could make C++ programmer's life easier and happier with this convenient,why do C++ prohibit it?

P.S: Reference - 9.2.4 section of C++ standard 2003.

A member-declarator can contain a constant-initializer only if it declares a static member (9.4) of const integral or const enumeration type, see 9.4.2.


Because otherwise there would be a question of which compilation unit (e.g. object file) the value lived in. Every file that included a header with a class definition would try to create an object that would be assigned to the static value on creation, potentially causing unpredictable behavior.

It's not just assignment that doesn't work; you also still need to define the static value outside of the class declaration. e.g.

class Foo
{
  static std::string s;
};

std::string Foo::s = "foo";

I don't know if that's a good reason, but I suspect that's the logic behind it, anyway.


I don't think you get a meaningful answer here. It's just happened so. And the new C++0x standard removes this limitation, which is the sign that there's no proper reason why.

Actually, this limitation is also inherited from C — you can't initialize structure members like that either.

Edit: now there is a hint in your example that suggests you're talking about static members. In your particular example you assign pointer to string, to the string. Other than that I will vote for scotchi answer now. There is, definitely, a logic behind it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜