c ++在类中使用const成员函数链接错误

时间:2018-05-04 11:36:24

标签: c++ class visual-studio-2012 dll

我有一个类似

的声明
    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:未解析的外部符号。但是,如果我从const的定义中删除了foo2,则会解决链接问题。有人能解释我这里发生了什么吗?我在Windows 7上的VS2012上

1 个答案:

答案 0 :(得分:0)

确保声明和定义的函数签名匹配。一个常见的错误是忘记了函数定义中的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
{
    ...
}

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