为什么ISO C ++标准禁止成员的初始化? [英] Why the ISO C++ standard forbids the initialization for members?
问题描述
为什么我不能这样做
class A {
public:
int x = 10;
...
};
我必须这样做吗?
class A {
public:
int x;
A(){
x = 10;
...
}
...
};
这是因为C ++试图比C语言更安全吗?还有其他原因吗?
It's because C++ is trying to be more type safe than languages like C ? There are other reasons ?
推荐答案
这与类型安全无关,两个例子都是安全的。
This has nothing to do with type safety, both examples are as safe.
创建语言时,您需要定义允许的内容和不允许的内容。因为写一个黑名单是一个永无止境的经历,一种语言通常是以白名单的方式写的,增加了越来越多的可能的东西。
When creating a language you need to define what is allowed and what is not. Since writing a blacklist would be a never-ending experience, a language is usually written in a white-list fashion, adding more and more possible things.
但是,不允许事情没有明确的权衡后果。每当你想允许新的东西,你需要检查:
However, one should not allow things without clearly weighing the consequences. Whenever you want to allow something new, you need to check:
- 易于实现
- 与其他现有功能的互动和已知的可能扩展
此外,这也意味着有更多的学习希望使用语言。
Furthermore, it also means that there is more to learn for those wishing to use the language.
但是,这里要求的是比较容易的。它可以看作是对等体,对于类,函数默认参数。这在C ++ 11中被采用,因为它是在写多个构造函数时保证默认值的一致性的最简单的方法。
What you are asking for here is, however, relatively easy. It can be seen as the counterpart, for classes, to functions default arguments. This has been adopted in C++11 because it was the simplest way to guarantee a coherence of the default values when writing multiple constructors.
当使用C ++ 11,我建议以这种方式初始化所有内置类型(如果只有 0
),很像我建议在声明局部变量时初始化它们:这种方式你不能忘记初始化他们在一个构造函数中。
Personally, when using C++11, I recommend initializing all built-in types this way (if only to 0
), much like I recommend initializing them when declaring local variables: this way you cannot forget to initialize them in one of the constructors.
这篇关于为什么ISO C ++标准禁止成员的初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!