简体   繁体   中英

export overloaded functions with C++

I've been lots of threads on this subject but I still miss the whole picture. Suppose I have a program structure like this and I want to build the project as a shared library:

class Parent
{
public:
    virtual double foo1() =0;
    virtual double foo2() =0;
    double foo3();
}

class Daughter1 : public Parent
{
public:
    double foo1();
    double foo2();
}

class Daughter2 : public Parent
{
public:
    double foo1();
    double foo2();
}

class evenmorecomplex:
{
public:
      evenmorecomplex(const &Parent);
//
}

in lots of threads, I saw there is a declaration of

extern "C"
{
 //functions for which I want to prevent the mangling
}

So my problem is double:

1) doesn't this method trash all the C++ object design?

2) obviously I can't declare two identical functions in the same scope...so, how can I export all the methods in this case?

Thanks everyone will make me things clearer.

[EDIT] Some more questions...just to understand better (sorry but I'm still a newbie in C++)...

3) if I had a non-virtual method (say foo3() ) in Parent, should I export also the Parent class, or the inherited (non-virtual) foo3 will be automatic "captured" while exporting Daughter1 and Daughter2? Should I selectively export that method in the Parent class?

4) suppose Parent is called in the constructor of another class (as reference)...since Parent can't be initialized the point is making the constructor to accept both Daughter1 and Daughter2. The question is: if I export only Daughter1 and Daughter2 (and evenmorecomplex) will this constructor still work?

This is compiler specific.

extern "C" is only useful when you want to export functions C style, if you want to export functions C style you won't be able to export functions with C++ calling conventions (such as any class functions)

On Windows / Visual-Studio, simply prefix your class with __declspec( dllexport ) when exporting or __declspec( dllimport ) when importing, like this:

class __declspec( dllexport ) MyClass{
    float somefloat = 12.0f;
    void fucn();
}

http://msdn.microsoft.com/en-us/library/81h27t8c.aspx

To use the same header, for both importing and exporting the class, you probably want to create a define/macro.

EDIT:

3&4, All base classes must be exportable, you can not inherit an exportable class from an non-exportable class. Its described in more detail here: http://msdn.microsoft.com/en-us/library/81h27t8c.aspx

Functions exported from an library outside of an "extern "C"" block like this are not callable from any language besides C++.

If you want to be able to call the functions from a different language, you either have to only export C functions, or export a COM interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM