gpt4 book ai didi

C++ : calling an abstract base class constructor/undefined symbol in shared object

转载 作者:行者123 更新时间:2023-11-30 03:29:59 24 4
gpt4 key购买 nike

我正在尝试使用抽象类,但在定义派生类的构造函数时遇到了一些问题。我根据这个 question 的答案编写了以下代码.

#include <string>
#include <iostream>

class ICommand {
private:
ICommand();
public:
const std::string name;
ICommand(const std::string& name) : name(name) { }
virtual void callMe();
virtual void callMe2();
};


class MyCommand : public ICommand {
public:
int x;
MyCommand(const std::string& name) : ICommand(name) { }
MyCommand(const std::string& name, int x) : ICommand(name), x(x) { }
void callMe() {
std::cout << name << "\n";
}
void callMe2() {
std::cout << name << x << "\n";
}
};

void f(std::string name) {
MyCommand A(name);
A.callMe();
}

编译没有错误。但是我的目标是为 R 包构建一个 .so)。在 R 安装过程中,.so 构建没有错误,带有 clang++ -shared,但随后有一个验证步骤产生

unable to load shared object '/path/object.so':
/path/object.so: undefined symbol: _ZTI8ICommand

我以前遇到过这种问题,并且有解决方法——不调用 Icommand(name) 相当简单,但我想了解那里发生了什么,如果可能的话,如何避免解决方法。

提前感谢您的想法。

回答

为了以后的读者方便:这里唯一需要做的改动就是将抽象类中虚函数的定义替换为

  virtual void callMe() = 0; 
virtual void callMe2() = 0;

这使它们成为纯虚函数。为什么这样可以解决问题,这让我很困惑。

最佳答案

随着:

class MyClass {
private:
MyClass();
};

您正在删除默认构造函数。如果您想调用默认构造函数,那么(声明或)定义或不定义一个但不要删除它。您的派生类默认构造函数将调用基类默认构造函数:

#include <string>
#include <iostream>
#include <memory>

class ICommand {
public:
std::string name;
ICommand() : name("The name") { std::cout << "Default base class constructor." << std::endl; }
virtual void callMe() = 0;
};

class MyCommand : public ICommand {
public:
MyCommand(){ std::cout << "Default derived class constructor." << std::endl; };
void callMe() override {
std::cout << name << std::endl;
}
};

void f2(const std::string& name) {
std::shared_ptr<ICommand> p = std::make_shared<MyCommand>();
p->callMe();
}
int main(){
f2("asdasd");
}

第 2 部分:
如果您尝试以多态方式使用上述类,请将您的 ICommand 成员函数设为纯虚拟:

virtual void callMe() = 0; 
virtual void callMe2() = 0;

void f 函数修改为:

void f(const std::string& name) {
std::shared_ptr<ICommand> p = std::make_shared<MyCommand>(name);
p->callMe();
}

Live example在 Coliru 上。

关于C++ : calling an abstract base class constructor/undefined symbol in shared object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45264480/

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