可以定义struct(a)没有用户定义的构造函数,(b)不能生成默认构造函数.例如,Foo在下面:
struct Baz
{
Baz(int) {}
};
struct Foo
{
int bar;
Baz baz;
};
Run Code Online (Sandbox Code Playgroud)
您仍然可以创建Foo使用聚合初始化的实例:
Foo foo = { 0, Baz(0) };
Run Code Online (Sandbox Code Playgroud)
我的普通编译器(VS2012)会勉强接受这个,但它会引发2个警告:
警告C4510:'Foo':无法生成默认构造函数.
警告C4610:struct'Foo'永远不能被实例化 - 需要用户定义的构造函数
当然,我刚刚证明警告#2错误 - 你仍然可以使用聚合初始化来实例化它.我尝试过的在线编译器很高兴接受上述内容,因此我猜测VS2012只是过于激进了这个警告.但我想确定 - 这段代码是否正常,还是技术上违反了标准中一些不起眼的部分?
c++ default-constructor language-lawyer aggregate-initialization visual-studio-2012
最近我使用Borland C++ 5.2在遗留环境中遇到了编译器错误.我有一个.cpp文件,其中包含一些我无法控制的C源头.头部包含一个包含const成员的结构定义,并且编译器抱怨"没有构造函数的类中的常量成员".经过调查,此错误似乎与编译器有关.以下是来自各种编译器的一些示例代码:
#include <stdio.h>
typedef struct {
const float a;
} _floater;
int main()
{
_floater f = {5.1F};
printf("%f\r\n",f.a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Borland 5.2
E:\Projects\Scratchpad>bcc32 -P const_float.c
Borland C++ 5.2 for Win32 Copyright (c) 1993, 1997 Borland International
const_float.c:
Error const_float.c 13: Constant member ' ::a' in class without constructors
*** 1 errors in Compile ***
Run Code Online (Sandbox Code Playgroud)
Microsoft VS 2003 .NET:
E:\Projects\Scratchpad>cl /TP const_float.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
Copyright (C) Microsoft Corp 1984-1998. …Run Code Online (Sandbox Code Playgroud) c++ ×2