I have seen following style class definition several times. What exactly are the pros/cons of this style?
typedef class _MyClass
{
public :
_MyClass();
开发者_JAVA百科} MyClass;
It's pretty rare in C++, but common in C (where struct Foo
does not automatically alias to just Foo
.) You might see it in a library that has different classes for different platforms (e.g. a "Canvas" class, which is very implementation-specific.) The library would use the typedef
to let its users simplify their code:
#if WINDOWS
typedef class WindowsCanvas {
private: HWND handle;
} Canvas;
#elif MAC
typedef class MacCanvas {
private: CGContextRef context;
} Canvas;
#endif
In such an example, one would only need to use the Canvas
type, never the platform-specific types.
In C++ there are no pros. This style came from C where you couldn't just use the struct's name as a type. E.g.
struct X
{
int x;
};
X a; //compiler error
struct X b; //OK
in order to avoid using the elaborated type specifier, like struct X a
, or enum E e;
etc. in C it is a common practice to typedef the name.
E.G.
typedef struct X_ { ... } X;
Now X a;
is OK too.
Naturally in C++ there is no need to do this.
One possible advantage is illustrated by a highly contrived example, but since the Standard speaks of it, it must be having an impliciation for sure.
$7.1.3/6- "Similarly, in a given scope, a class or enumeration shall not be declared with the same name as a typedef-name that is declared in that scope and refers to a type other than the class or enumeration itself. [
typedef struct S{} MYS;
int MYS; // Error due to $7.1.3/6
struct A{};
int A; // No error, subsequent use required fully elaborated name
int main(){}
精彩评论