首页 > 解决方案 > c ++链接错误与类中的const成员函数

问题描述

我有一个类似的声明

    class ABC_EXPORT abc
    {
    ....

public:
     xyz foo1(const arg1 a, const arg3 b) const; //defined in cpp file
     xyz foo2(const arg1 a, const arg2 b) const { return foo1(a, convert_to_arg3(b));}
    };

这被内置到一个 DLL 库中,另一个项目调用foo2. 我收到链接器错误 LNK2019 : unresolved external symbol。但是,如果我const从链接的定义中删除,foo2则解决。有人可以解释一下这里发生了什么吗?我在 Windows 7 上使用 VS2012

标签: c++classvisual-studio-2012dll

解决方案


确保声明的函数签名和定义匹配。一个常见的错误是忘记const函数定义上的说明符。例如,

struct A
{
    void do_foo_const(int a, int b) const;
};

// An incorrect definition.
// Notice the missing 'const' here V
void A::do_foo_const(int a, int b)
{
    ...
}


// correct definition.
void A::do_foo_const(int a, int b) const
{
    ...
}

这种分离允许函数的 const 版本和非 const 版本彼此并存,并返回不同的结果。C++ 标准库中使用此功能的一个示例是std::vector<T>::at. 请注意 const 版本如何返回一个 const 引用,但非 const 版本返回一个非常量引用。


推荐阅读