这似乎与包含常量成员的POD结构类似,但有点相反.
#include <iostream>
struct A
{
int a;
};
union U
{
volatile A a;
long b;
};
int main()
{
U u1;
U u2;
u1.a.a = 12;
u2 = u1;
std::cout << u2.a.a << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
g ++ 4.8.3编译此代码时没有错误,并且运行正常:
$ g++ -std=c++03 a.cpp -o a_gcc
$ ./a_gcc
12
Run Code Online (Sandbox Code Playgroud)
但是clang ++ 3.5.1会产生错误(我手动包装错误消息以防止代码框滚动):
$ clang++ -std=c++03 a.cpp -o a_clang
a.cpp:8:7: error: member function 'operator=' not viable: 'this'
argument has type 'volatile A', but function is not marked …Run Code Online (Sandbox Code Playgroud) 最近我使用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)