声明一个类的const实例 [英] 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;
这怎么会是编译器错误? (未初始化的const'f'
)
how come this is a compiler error? (uninitialized const ‘f’
)
const foo f;
为什么必须这样做?
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;
那么 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.
编辑:如果它很愚蠢,请随时将其关闭...
please feel free to close it if it's stupid...
推荐答案
您的课程是 POD (本质上是因为它没有提供默认的构造函数)。声明时 not 不会初始化POD变量。也就是说:
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;
不会将x初始化为有意义的值。这必须单独进行。现在,当您将其声明为 const
时,可能永远不会发生,因为您无法再分配或更改 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.
考虑与 int
等效:
int x; // legal
const int y; // illegal
您已经注意到,使用 std :: string
而不是 foo
进行编译。这是因为 std :: string
不是POD。解决难题的一个简单方法是为 foo
提供默认的构造函数:
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() { }
};
现在您的 const foo x;
代码会编译
这篇关于声明一个类的const实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!