Visual Class 在 DLL 中的成员函数中返回自身C++

visual Class returning itself in member functions in C++ DLL

本文关键字:返回 C++ 函数 Class DLL Visual 成员      更新时间:2023-10-16

若要在 DLL 中使用类,为了编译器之间的兼容性,请使用 https://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL#CppMatureApproach 中的方法。这要求类派生自抽象类作为"接口",并覆盖抽象类的功能。如果 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++允许所谓的协变返回类型,这意味着override方法的子类可以用子类型替换原始返回类型。但即使你没有它,你也可以返回子类的实例作为父类。但是,您可能遇到的问题是切片。如果要返回值(而不是引用或指针),则在使用父类接口时,子类中的其他成员将丢失。您可以使用其他间接寻址(例如带有指针的结构)或其他一些策略来避免它。

正如您链接的文章所述,这种方法的缺点:

抽象接口方法不能返回或接受常规C++ 对象作为参数。它必须是内置类型(如 int, 双精度、字符*等)或其他抽象接口。它是一样的 COM 接口的限制。

那么也许返回一个指向类实现的 asbtract 接口的指针?