错误C2582:'B'中没有'operator ='功能 [英] error C2582: 'operator =' function is unavailable in 'B'
问题描述
以下代码在main()中的 e = f行给出了编译错误(至少在使用MS VS 2008时):
Following code gives a compilation error (at least when using MS VS 2008) for line "e=f" in main():
错误C2582:'运算符='函数在'B'中不可用
error C2582: 'operator =' function is unavailable in 'B'
class A {
public:
A() { }
static const double x;
};
const double A::x = 0.0;
class B {
public:
B() : x(0.0) { }
const double x;
};
int main( int argc, char *argv[] )
{
A c,d;
B e,f;
c = d;
e = f;
return 0;
}
应同时为A和B两个类生成默认赋值运算符!
The default assignment operator should be generated for both classes, A and B !?
在12.8.10中:如果类定义未显式声明
复制赋值运算符,则将隐式声明一个。
in 12.8.10: "If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly."
推荐答案
隐式生成的运算符将递归地分配每个非静态成员。但是, x
是 const
,因此无法分配给它。这样可以防止隐式运算符的生成(特别是,它导致将其定义为已删除)。
The implicitly generated operator would recursively assign each non-static member. However, x
is const
, so it can't be assigned to. This prevents the implicit operator from being generated (specifically, it causes it to be defined as deleted).
在C ++ 11 12.8 / 23中指定:
This is specified in C++11 12.8/23:
如果X具有:
A defaulted copy/move assignment operator for class X is defined as deleted if X has:
- ,则将类别X的默认复制/移动赋值运算符定义为已删除。
- const非类类型(或其数组)的非静态数据成员,或
- ...
(尽管我刚刚注意到您的编译器早于C ++ 11;规则相似,但是用较老的方言指定
(Although I just noticed that your compiler predates C++11; the rules are similar, but specified in different language, in older dialects with no concept of "deleted" functions).
如果您要为其成员(或基类)无法重新分配的类分配赋值运算符,则必须定义
If you want an assignment operator for a class whose members (or base classes) can't be reassigned, you'll have to define it yourself.
在 A类
中,常量成员是静态的,因此不构成对象的一部分。因此,它不会阻止将(空)对象分配给该对象。
In class A
, the constant member is static, so doesn't form part of an object. Therefore, it doesn't prevent an (empty) object from being assigned to.
这篇关于错误C2582:'B'中没有'operator ='功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!