問題描述
我很清楚class 和 struct 之間的區(qū)別,但是我很難權(quán)威地說這是否定義明確:
I'm well aware of the difference between class and struct, however I'm struggling to authoritatively say if this is well defined:
// 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;
}
如果這是未定義的行為,有人可以指出我權(quán)威(即 ISO 中的章節(jié)和詩句)參考的方向嗎?
If this is undefined behaviour can someone point me in the direction of an authoritative (i.e. chapter and verse from ISO) reference?
編譯器在處理此問題時(shí)遇到問題(Carbide 2.7)相對較舊,我嘗試過的所有其他編譯器都對此非常滿意,但顯然這并不能證明任何事情.
The compiler with problems handling this (Carbide 2.7) is relatively old and all the other compilers I've tried it on are perfectly happy with this, but clearly that doesn't prove anything.
我的直覺是這應(yīng)該是未定義的行為,但我找不到任何可以證實(shí)這一點(diǎn)的東西,我很驚訝 GCC 版本或 Comeau 已經(jīng)警告過了.
My intuition was this ought to be undefined behaviour but I can't find anything to confirm this and I'm surprised that none of the GCC versions or Comeau so much as warned about it.
推薦答案
在我看來,它像是已定義的行為.特別是,§9.1/2 說:
It looks to me like it's defined behavior. In particular, §9.1/2 says:
僅由 class-key identifier ;
組成的聲明要么是對當(dāng)前作用域中的名稱或標(biāo)識符的前向聲明作為類名.它將類名引入當(dāng)前作用域.
A declaration consisting solely of
class-key identifier ;
is either a redeclaration of the name in the current scope or a forward declaration of the identifier as a class name. It introduces the class name into the current scope.
標(biāo)準(zhǔn)在定義一個(gè)類時(shí)區(qū)分使用class
、struct
或union
,但在這里,談?wù)撽P(guān)于聲明,沒有這樣的區(qū)別——使用一個(gè) class-key
等同于任何其他.
The standard distinguishes between using class
, struct
or union
when defining a class, but here, talking about a declaration, no such distinction is made -- using one class-key
is equivalent to any other.
這篇關(guān)于混合類和結(jié)構(gòu)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!