C++ 的签名带有枚举的结构的复制构造函数
包含枚举的结构的隐式复制构造函数是否有理由不使用const版本 - 或者为什么根本没有复制构造函数?我希望创建一个隐式复制构造函数,即:
X(const X& x)
我知道何时发生这种情况有规则,例如,如果成员变量没有复制构造函数或非常量复制构造函数。我想我的问题是这与枚举有何关系 - 这条规则是否适用?
添加我自己的复制构造函数似乎可行。
示例 - 隐式创建什么复制构造函数(如果有):
struct MyStruct {
int myInt;
double myDouble;
MyEnum myEnum;
};
Is there a reason why the implicit copy constructor for a struct containing an enum would not use the const
version - or why there is no copy-constructor at all? I would expect an implicit copy-constructor being created, i.e.:
X(const X& x)
I know there are rules for when this might happen, for instance if a member variable does not have a copy constructor, or a non-const copy constructor. I guess my question is how this relates to enums - and if it is this rule that applies?
Adding my own copy constructor seems to work.
Example - what, if any, copy-constructors are created implicitly:
struct MyStruct {
int myInt;
double myDouble;
MyEnum myEnum;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您对枚举的猜测是错误的;问题出在别的地方。如果没有显式定义复制构造函数,则以下代码可以正常编译,如果存在采用非常量引用的复制构造函数,则编译失败。
正如其他人在评论中指出的那样,需要一个证明错误的现实示例才能了解真正的问题是什么。
Your guess about enums is wrong; the problem is somewhere else. The following code compiles with no problem if no copy constructor is explicitly defined, and fails to compile if there is a copy constructor taking a non-const reference.
As others pointed out in comments, a realistic example demonstrating the error is required to understand what's the real problem.
这有点超出我的专业知识。
当您尝试从
X
的非常量左值实例构造X
时,签名X(X& )
将更接近匹配,并被选中。This is a little bit out of my expertise.
When you try to construct an
X
from a non-const lvalue instance ofX
, the signatureX(X& )
would be a closer match, and be chosen.