Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c++ - declaring a const instance of a class

Let's say I have a class defined as follows:

class foo{};

now, this is perfectly acceptable;

foo f;

how come this is a compiler error? (uninitialized const ‘f’)

const foo f;

Why do we have to do this?

const foo f = foo();

I know why we can't do this..

const foo f(); // though it compiles..

Interestingly, the following is valid:

const std::string f;

So what is missing from foo?

I realize that there are three questions there and it's bad form, but I'm hoping someone can clear this up for me in one answer.

EDIT: please feel free to close it if it's stupid...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your class is a POD (essentially because it doesn’t provide a default constructor). POD variables are not initialized upon declaration. That is, this:

foo x;

does not initialize x to a meaningful value. This has to be done separately. Now, when you declare it as const, this may never happen because you cannot assign to or change x any more.

Consider the equivalence to int:

int x; // legal
const int y; // illegal

As you have noticed, using std::string instead of foo compiles. That’s because std::string is not a POD. A simple solution to your dilemma is to provide a default constructor for foo:

class foo {
public:
    foo() { }
};

Now your const foo x; code compiles.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...