declaring a const instance of a class(声明一个类的 const 实例)
问题描述
假设我有一个定义如下的类:
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;
为什么我们必须这样做?
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;
那么 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(本质上是因为它不提供默认构造函数).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;
代码编译好了.
Now your const foo x;
code compiles.
这篇关于声明一个类的 const 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声明一个类的 const 实例


- C语言手把手带你掌握带头双向循环链表 2023-04-03
- Easyx实现扫雷游戏 2023-02-06
- ubuntu下C/C++获取剩余内存 2023-09-18
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- C++ 数据结构超详细讲解顺序表 2023-03-25
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- C语言qsort()函数的使用方法详解 2023-04-26
- Qt计时器使用方法详解 2023-05-30
- C语言详解float类型在内存中的存储方式 2023-03-27