为了在DLL中使用类,以实现编译器之间的兼容性,使用了https://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL#CppMatureApproach中的方法。这要求从抽象类派生该类作为“接口(interface)”,并覆盖该抽象类的功能。如果DLL的类具有返回该类值的函数,则如何派生它并覆盖抽象类的函数,因为这些函数必须具有相同的返回值,并且不能返回抽象类的值。除了制作第三个未导出的类(可以轻松地转换为将在不丢失数据的情况下导出的原始类)之外,如何以与其他编译器一起使用的方式从DLL导出类?

原始代码:仅适用于相同的编译器。

#pragma once

#ifdef UNSIGNEDBIGINT_EXPORTS
#define UNSIGNEDBIGINT_API __declspec(dllexport)
#else
#define UNSIGNEDBIGINT_API __declspec(dllimport)
#endif

#include "stdafx.h"

typedef std::deque<short int> list;

//Unsigned Bigint class.



class UNSIGNEDBIGINT_API Unsigned_Bigint
{
private:
    list digits;
    Unsigned_Bigint removeIrreleventZeros(Unsigned_Bigint);

    //Arithmetic Operations
    Unsigned_Bigint add(Unsigned_Bigint);
    Unsigned_Bigint subtract(Unsigned_Bigint);
    Unsigned_Bigint multiply(Unsigned_Bigint);
    Unsigned_Bigint divide(Unsigned_Bigint, bool);

    //Comparison Operations
    bool greater(Unsigned_Bigint);

public:
    Unsigned_Bigint();
    Unsigned_Bigint(int);
    Unsigned_Bigint(list);
    Unsigned_Bigint(const Unsigned_Bigint&);
    ~Unsigned_Bigint();
    inline list getDigits() const;

    //Overloaded Arithmetic Operators
    inline Unsigned_Bigint operator+(Unsigned_Bigint);
    inline Unsigned_Bigint operator-(Unsigned_Bigint);
    inline Unsigned_Bigint operator*(Unsigned_Bigint);
    inline Unsigned_Bigint operator/(Unsigned_Bigint);
    inline Unsigned_Bigint operator%(Unsigned_Bigint);

    //Overloaded Comparison Operators
    inline bool operator==(Unsigned_Bigint);
    inline bool operator!=(Unsigned_Bigint);
    inline bool operator>(Unsigned_Bigint);
    inline bool operator<(Unsigned_Bigint);
    inline bool operator>=(Unsigned_Bigint);
    inline bool operator<=(Unsigned_Bigint);

    //Overloaded Asignment Operators
    inline void operator=(Unsigned_Bigint);
    inline void operator+=(Unsigned_Bigint);
    inline void operator-=(Unsigned_Bigint);
    inline void operator*=(Unsigned_Bigint);
    inline void operator/=(Unsigned_Bigint);
    inline void operator%=(Unsigned_Bigint);

    //Increment/Decrement
    inline Unsigned_Bigint& operator++();
    inline Unsigned_Bigint& operator--();
    inline Unsigned_Bigint operator++(int);
    inline Unsigned_Bigint operator--(int);

    //Exponent
    Unsigned_Bigint exponent(Unsigned_Bigint);

};

//Ostream
UNSIGNEDBIGINT_API inline std::ostream& operator<<(std::ostream&, Unsigned_Bigint);

编辑:还存在一个问题,即抽象基类将自身作为参数,这是非法的,因为它是一个抽象类。使用引用需要对代码进行大量修改。还有其他选择吗?

最佳答案



并非如此,C++允许使用所谓的covariant return types,这意味着override是方法的子类可以用子类型替换原始的返回类型。但是,即使没有,也可以将子类的实例作为父类返回。但是,您可能遇到的问题是slicing。如果要返回值(与引用或指针相反),则在使用父类接口(interface)时,子类中的其他成员将丢失。您可以使用其他间接寻址(例如,带有指针的结构)或其他一些策略来避免这种情况。

07-25 22:18
查看更多