问题描述
(由于之前的示例存在缺陷,因此进行了重大更改,这可能会使某些答案/评论看起来很奇怪)
这可能过于做作,但由于缺少 const 构造函数,以下是合法的:
This might be an overly contrived, but the following is legal because of lack of const constructor:
class Cheater
{
public:
Cheater(int avalue)
: cheaterPtr(this) //conceptually odd legality in const Cheater ctor
, value(avalue)
{}
Cheater& getCheaterPtr() const {return *cheaterPtr;}
int value;
private:
Cheater * cheaterPtr;
};
int main()
{
const Cheater cheater(7); //Initialize the value to 7
cheater.value = 4; //good, illegal
cheater.getCheaterPtr().value = 4; //oops, legal
return 0;
}
似乎提供一个 const 构造函数在技术上与 const 方法一样简单,并且类似于 const 重载.
It seems like providing a const constructor a thing would be as easy technically as const methods, and be analogous to a const overload.
注意:我不是在寻找Image(const Data & data) const
"而是const Image(const Data & data) const
"代码>'
Note: I'm not looking for 'Image( const Data & data ) const
' but rather 'const Image( const Data & data) const
'
所以:
- 为什么 C++ 中没有 const 构造函数?
这里有一些相关的上下文材料:
Here's some related material for context:
- http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1995/N0798.htm
- 如何处理const对象中非常量引用成员的初始化?
- C++、类、常量和奇怪的语法
推荐答案
它本身不会是一个 const 方法
It would not be a const method itself
如果这个构造函数本身不是一个 const
方法,那么内部指针等也不会是 const
.因此,它无法将 const
值设置为那些非 const
成员.
If this constructor were not a const
method itself, then the internal pointers and such would also not be const
. Therefore, it could not set const
values into those non-const
members.
让它在语法上工作的唯一方法是让这个构造函数要求所有非可变
成员的成员初始化.本质上,当使用此构造函数时,任何未声明 mutable
的成员都将隐式声明 const
.这相当于使构造函数成为 const
方法;只有初始化器可以初始化成员.构造函数的主体不能对非可变成员做任何事情,因为那些成员在那时将是 const
.
The only way to make it work syntactically is for this constructor to require member initialization for all non-mutable
members. Essentially, any member not declared mutable
would be implicitly declared const
when using this constructor. Which is equivalent to making the constructor a const
method; only initializers could initialize members. The constructor's body could do nothing with non-mutable members, because those members would be const
at that point.
您所要求的在语法上是可疑的.您实际上是在试图欺骗 API,将常量数据存储在为可变数据设计的对象中(这就是您没有将成员指针声明为 const
的原因).如果您希望某个对象具有不同的行为,则需要声明该对象以具有该特定行为.
What you are asking for is syntactically dubious. You're essentially trying to hoodwink the API, storing constant data in an object that is designed for mutable data (which is why you didn't declare the member pointer to be const
). If you want different behavior for an object, you need to declare the object to have that specific behavior.
这篇关于为什么 C++ 没有 const 构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!