加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 定义的构造函数的“未定义引用”

发布时间:2020-12-16 04:58:53 所属栏目:百科 来源:网络整理
导读:我有一个构造函数,其签名是这样的: cpuInput (const std::string label); 实际的构造函数使用引用超构造函数的初始化列表,所以它看起来像这样: cpuInput::cpuInput (const string label) : StateMonitor::input(label) { } 该类编译为目标文件.如果我将该
我有一个构造函数,其签名是这样的:
cpuInput (const std::string &label);

实际的构造函数使用引用超构造函数的初始化列表,所以它看起来像这样:

cpuInput::cpuInput (const string &label) : StateMonitor::input(label) { }

该类编译为目标文件.如果我将该文件与调用构造函数的驱动程序一起编译:

cpuInput *cpu = new cpuInput();

当然我从g得到一个错误:

demo.cpp:15:31: error: no matching function for call to ‘cpuInput::cpuInput()’
demo.cpp:15:31: note: candidates are:
In file included from demo.cpp:3:0:
input_cpusage/cpuInput.hpp:7:3: note: cpuInput::cpuInput(const string&)

现在这里是奇怪的部分:如果我将构造函数调用更改为:

cpuInput *cpu = new cpuInput("cpu");

并将其他所有内容保持不变,我现在得到:

demo.cpp:15: undefined reference to `cpuInput::cpuInput(std::string const&)'

我意识到const string&与字符串const&并不完全相同,但我原以为这是在C中传递字符串引用(在这种情况下,通过从const char *转换)的标准方法,并且:

class A {
    public:
        A (const string &s) : x(s) { cout << x << endl; }
    private:
        const string x;
};

class B : A {
    public:
        B (const string &s) : A(s) { }
};

int main (void) {
    new B("test");
    return 0;
}

不重现这个问题,虽然它似乎与我相同的WRT相关元素.

那么为什么一方面会说:

candidates are … cpuInput::cpuInput(const string&)

然后到新的cpuInput(“string”)说:

undefined reference to `cpuInput::cpuInput(std::string const&)

解决方法

对于后代,问题在于我在头文件中定义了超类构造函数(和析构函数) – 超类是纯虚拟的.毫无疑问,这是一个常见的C新手错误.

这意味着虽然编译和链接派生类,但超类却没有.由于派生类被编译为.o,编译器并不关心,但在调用派生类构造函数的可执行文件中使用该.o会产生链接器错误:

undefined reference to subclass::subclass(...)

虽然从根本上未定义的是超类::超类().

作为注释,如果将其声明为虚拟,则还必须编译超类析构函数的定义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读