Dll导出友元operator>>

4
我正在创建这个类:
///> MyObject.h file
class __declspec(dllexport) CMyObject
{
public:
    int m_Intero;
public:
    CMyObject();
    ~CMyObject();
public:
    friend std::wifstream& operator>>(std::wifstream& is, CMyObject& eprt);
}
///> MyObject.cpp
std::wifstream& operator>>(std::wifstream& is, CMyObject& myobj)
{
    if (is.is_open())
        ///> Input operations.

    return is;
}

当我编译库时,没有出现错误,但是当我在最终项目中使用我的库时,出现了以下错误:
LNK2019 unresolved external symbol reference "class std::basic_ifstream<wchar_t,struct std::char_traits<wchar_t> > & __cdecl operator>>(...) in function "public: void __thiscall ...

我想我需要以某种方式指定我的operator>>函数需要被导出。

我应该如何修改我的代码?

1个回答

3

几个要点:

  • 你正在导出类,而不是全局(友元)函数。你只是让编译器知道全局函数(运算符重载)是一个友元。你需要导出该函数。
  • 涉及到C++对象时,最好不要导出这样的函数,因为编译器的差异会使得类具有不同的大小。

从第二点来看,我应该假设我不需要导出 operator >> friend,那么我就不能使用它从文件中加载数据。这是正确的吗? - IssamTP
我已经完成了一个“LoadFromFile”函数,并在其中使用了运算符>>。这样做正确吗? - IssamTP
朋友__declspec(dllexport) std::wifstream& operator>>(std::wifstream& is, CMyObject& eprt);应该可以解决你的问题。 - munsingh
1
@munsingh,是的,但是如何保证CMyObject在DLL和DLL客户端(主要是EXE)中是相同的?如果DLL发生更改,并且还更改了大小(或vptr表),那怎么办?如果DLL和客户端不是同一构建套件的一部分,则导出类是不正确的。 - Ajay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接