开发者

declaring a class with struct keyword and vice versa

But of course we shouldn't even think of doing such things, I know, but still this is quite interesting:

class A; //declaration
struct A {...}; //definition

struct B; //declaration
class B {...}; //definition

When I think about it, I don't see any problems if such a thing were really al开发者_如何学运维lowed(because struct and class are essentially the same thing). But is it (standard-wise)?

MSVC accepts and compiles it, with a warning.


It is allowed according to the standard, but as some compilers warn about it, it is not very useful.

I believe the warning is/was caused by MSVC using a different name mangling for structs and classes, which would make it even less useful...


On request from @Armen:

7.1.5.3 Elaborated type specifiers, p3

... in any elaborated-type-specifier, the enum keyword shall be used to refer to an enumeration (7.2), the union class-key shall be used to refer to a union (clause 9), and either the class or struct class-key shall be used to refer to a class (clause 9), declared using the class or struct class-key.


As per C++03 Standard 9.1 - 2

"A class definition introduces the class name into the scope where it is defined and hides any class, object, function, or other declaration of that name in an enclosing scope (3.3)."

So it is valid as per the standard.

Playing around a bit with the example code:

#include<iostream>

class A; //declaration 
struct A { int i;}; //definition  
struct B; //declaration 
class B {int j;}; //definition 

int main()
{
    A obj;
    obj.i = 10;
    B obj2;
    obj2.j = 10;
    std::cout<<"sizeof"<<sizeof(struct B);
    return 0;
}

Here is the output:

prog.cpp: In function ‘int main()’:
prog.cpp:6: error: ‘int B::j’ is private
prog.cpp:13: error: within this context

The only difference between C++ struct & class is that default access specifier for structure is public while for class it is private.

So, From the above example:
In this case compiler treats A as a structure &
B as a class

As you see, the compiler follows the quote from the standard and the type with the definition is what the compiler recognizes, over the declaration type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜