我有这段代码
typedef struct
{
const char* fooString;
const bool fooBool;
}fooStruct;
这个初始化程序:
static const fooStruct foo[] =
{
{"file1", true},
{"file2", false},
....
};
使用此代码,我在VS2008中有3个警告:
error C2220: warning treated as error - no 'object' file generated
warning C4510: '<unnamed-tag>' : default constructor could not be generated
warning C4512: '<unnamed-tag>' : assignment operator could not be generated
warning C4610: struct '<unnamed-tag>' can never be instantiated - user defined constructor required
答案 0 :(得分:11)
这正是编译器所说的:它不能为你的struct生成默认的构造函数或赋值运算符,因为它中有一个const
成员(const bool fooBool
)。 const
或引用的struct成员不能默认初始化,因此必须在用户编写的构造函数或赋值运算符中显式初始化它们。
一种解决方案是编写自己的默认构造函数和赋值运算符(并且与rule of three一致,您还应该编写一个复制构造函数;析构函数不是绝对必要的,但是很好的做法)。另一种更简单的解决方案就是让fooBool
非 - const
。然后,编译器将很乐意为您生成默认构造函数和赋值运算符。
由于您已经使用const
创建了static const fooStruct foo[] = ...
个这些实例的数组,const
上的额外fooBool
毫无意义。
答案 1 :(得分:8)
C4610警告不正确。这是Visual C ++中的已知错误。请参阅Microsoft Connect错误"Improper issuance of C4610."
Adam Rosenfield explains为什么会发出其他两个警告(C4510和C4512)。
答案 2 :(得分:0)
此外,如果您进行部分初始化,那么MSVC2008将抛出错误(如MSVC2010),这是C ++ 03和C ++ 11定义的错误行为。我在堆栈溢出的另一个线程中发布了更多内容,您可以阅读here
// Partial initialization, leaving it to the compiler
// to do aggregate value-initialization
fooStruct foo ={"file1", /*missing true/false, compiler should set false*/ };
MSVC会在此代码中引发错误以及您提到的警告。