gpt4 book ai didi

c++ - 类在 C++ DLL 的成员函数中返回自身

转载 作者:太空狗 更新时间:2023-10-29 22:56:26 25 4
gpt4 key购买 nike

要在 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);

编辑:还有一个问题是抽象基类把自己作为参数,因为是抽象类,所以不合法。使用引用需要对代码进行大量修改。有其他选择吗?

最佳答案

as the functions must have the same return value and the value of an abstract class can not be returned

不是真的,C++ 允许所谓的 covariant return types ,这意味着 override 方法的子类可以用子类型替换原始返回类型。但是即使你没有那个,你也可以返回一个子类的实例作为父类。不过,您可能遇到的问题是 slicing .如果您要返回值(而不是引用或指针),那么当您使用父类接口(interface)时,子类中的其他成员将丢失。您可以使用额外的间接(例如,带有指针的结构)或其他一些策略来避免它。

关于c++ - 类在 C++ DLL 的成员函数中返回自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48278722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com