相关疑难解决方法(0)

混合类和结构

我很清楚类和结构之间区别,但是我很难权威地说这是否定义得很好:

// declare foo (struct)
struct foo;

// define foo (class)
class foo {
};

// instance of foo, claiming to be a struct again! Well defined?
struct foo bar;

// mixing class and struct like this upsets at least one compiler (names are mangled differently)
const foo& test() {
   return bar;
}

int main() {
   test();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果这是未定义的行为,有人可以指向权威(即ISO的章节和经文)参考的方向吗?

处理这个问题的编译器(Carbide 2.7)相对较旧,我尝试过的所有其他编译器对此都非常满意,但显然没有任何证据.

我的直觉是这应该是未定义的行为,但我找不到任何证实这一点,我很惊讶没有GCC版本或Comeau这么多警告它.

c++ struct class undefined-behavior

17
推荐指数
2
解决办法
2951
查看次数

标签 统计

c++ ×1

class ×1

struct ×1

undefined-behavior ×1