Struct Cannot take Constructor When using with __declspec(dllexport)
I try to define a constructor for C++ struct
, and coincidently, this is also a struct I want to export. So here's my code:
extern "C"__declspec(dllexport) typedef struct
{
double x;
double y;
PointCg(double xx, double yy);
}PointCg;
However, I got a compilation error saying that
error C4430: missing type 开发者_StackOverflowspecifier- int assumed. Note: C++ does not support default-int
But I think this is a perfectly valid declaration?
I'm using visual-c++ 2008, if it matters to you.
The __declspec
doesn't have anything to do with it. You're defining an anonymous struct. The typedef name won't work for defining a constructor. Inside the definition, PointCg
just looks like a function name, and functions have to have a return type. This is how you define a struct in C++:
struct PointCg{
//....
PointGc(double xx, double yy);
};
Unlike C, you don't need to typedef struct names to avoid typing struct
everywhere, and can just use PointCg
instead of struct PointCg
when referring to that type.
typedefs are just aliases to the base type. This implies that typedefs are a compile time, not a link time construct.
In your sample code you are attempting to dllexport a typedef, of an anonymous struct - which is going to confuse the compiler on two levels: first, you're exporting an alias, which it doesn't want to do, and next, the struct itself is anonymous, so it can't even export that. Thirdly, the thing that looks like the constructor isn't. Its just a function with a weird name. A ctor has to have the name of the struct and, well, its anonymous.
Given this question is c++ which relaxed a lot of the rules when using structs... why dont you just skip the typedef and give the struct the name:
extern "C"__declspec(dllexport) struct PointCg
{
double x;
double y;
PointCg(double xx, double yy);
};
error C4430: mising type specifier- int assumed. Note: C++ does not support default-int
This most often means you introduced a name that doesn't mean anything to the compiler yet. And indeed I believe this is the case here. You are employing an ancient C technique to define a structure: the typedef struct
. When the compiler gets to your (as-yet unnamed) struct's constructor, the PointCg
name doesn't mean anything. It doesn't mean anything until the typedef is named after the closing }
.
I suggest you change your code as follows:
extern "C"__declspec(dllexport) struct PointCg
{
double x;
double y;
PointCg(double xx, double yy);
};
In C++, there is literally never a reason to use the old typedef struct
technique. This only causes pain and confusion, and gets you nothing.
精彩评论