【问题标题】:Instantiate abstract class but then re-declare with specific derived class? [duplicate]实例化抽象类,然后用特定的派生类重新声明? [复制]
【发布时间】:2020-09-02 19:23:44
【问题描述】:

我有一个带有纯虚函数的基类和来自这个基类的两个不同的派生类。 出于范围界定的目的,我需要实例化抽象类,然后选择需要在程序中使用的派生类。请注意,我通过引用传递 myObj。

class Base {
    public:
        virtual int build(const std::string &fname) = 0; //pure virtual build function
}

class A : public Base {
    public:
        int build(const std::string &fname); //Implementation of build
}

class B : public Base {
    public:
        int build(const std::string &fname); //Implementation of build
}

int run(const Base &myObj) {
       //Random things will be done based on myObj being passed by reference
       //myObj.get_info();
       //myObj.val;
}

int main(const char *tag) {
    
    std::string s = tag;
    Base myObj;
    if(s.compare("Class A")) {
        A myObj;
    }
    if(s.compare("Class B")) {
        B myObj;
    }
    run(myObj);
    return 0;
}

【问题讨论】:

  • 你到底想在这里做什么?您在 cmets 中谈论 get_info().val,但我没有看到其中任何一个。您还声明build virtual 并谈论“抽象”类,但您不会在任何地方使用指针或多态性。您能详细说明一下这里的目标是什么吗?
  • 我的目标是在编码结束时拥有大约 10 个其他派生类。但是每个派生类都会有一个.valget_info(),它们将在运行中使用。但是需要构建哪个派生类将取决于 tag 进入主类。我现在没有指针的原因是因为我有一个带有一个派生类的工作代码,并且在run(我没有包括)中实现的所有内容都通过引用传递myObj。因此,当我尝试使用指针时,我无法编译它,因为我所有的函数都在使用 &myObj
  • 您的问题不在于实例化抽象类。它是关于设置逻辑以根据字符串实例化不同的派生类。将myObj 声明为指向Base 的指针,然后当s.compare("Class A") 测试为true 时执行myObj = new A,当s.compare("Class B") 测试为true 时执行myObj = new B,等等。完成后释放对象。您可以使用智能指针使其更清晰,但我将把它留作练习。顺便说一句:你需要真正阅读如何在 C++ 中做事。像你正在做的猜测(或假设 C++ 像你知道的另一种语言一样工作)是行不通的。

标签: c++ abstract-class pure-virtual


【解决方案1】:

这无法做到,至少按照您的规定。在 C++ 中,当使用这样的继承时,您通常需要使用堆分配的对象。

我建议为此使用std::unique_ptr,例如:

    std::unique_ptr<Base> myObj;
    if (s == "Class A") {
        myObj = std::make_unique<A>();
    }
    else if (s == "Class B") {
        myObj = std::make_unique<B>();
    }
    else {
        // Handle the case where `s` is another string - otherwise below
        // you'll get undefined behavior (bad!) when trying to dereference
    }
    run(*myObj);

请注意,我修复了您在问题中遇到的一些语法错误,但您似乎正在尝试使用 C++,就好像它是其他语言一样 :)

【讨论】:

  • 是的,C++ 不是我的普通语言,我知道你不能实例化抽象类,但这是我遇到的问题的本质。
猜你喜欢
  • 2017-04-28
  • 2015-03-23
  • 2014-10-13
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
相关资源
最近更新 更多