【问题标题】:Declare object of derived class without specifying it声明派生类的对象而不指定它
【发布时间】:2019-12-29 02:55:03
【问题描述】:

有一个基类 Base 和两个可能的派生类 DerivedA 和 DerivedB。如何在不指定(在声明时)两个派生类中的哪一个将被使用的情况下声明一个变量?

我尝试了以下示例:

#include <iostream>
#include <vector>
#include <memory>
using namespace std;
#include <stdlib.h>


struct Base
{
    int base = 0;
};

struct DerivedA : Base
{
    int x = 1;
};

struct DerivedB : Base
{
    int y = 1;
};


class Test
{
public:
    Test(int a)
    {
    Base TestObj;
    if (a==0)
    {
        DerivedA TestObj; // intention: change type of TestObj to DerivedA
    }
    else
    {
        DerivedB TestObj; // intention: change type of TestObj to DerivedB
    }

    TestObj.base = 7;

    if (a==0)
    {
        TestObj.x = 2;
    }
    else
    {
        TestObj.y = 4;
    }

    myObjs.push_back(make_shared<Base>(TestObj));
    }
private:
    vector<shared_ptr<Base>> myObjs;

};

编译器会抛出一个错误,提示“错误:‘struct Base’没有名为‘x’的成员”(或分别为‘y’)。

一个简单的解决方案是在第一个 if (a==0) / else 语句中包含所有内容,对这两种情况使用单独的 myObjs.push_back 调用。但是,我对可以保持更灵活的解决方案感兴趣,最好是通过例如只改变'Base TestObj;'行更一般的东西。提前致谢。

【问题讨论】:

  • 你不能在运行时改变对象的类型。
  • C++ 是一种静态类型的语言。不是动态类型的。
  • @NeilButterworth:你在吹毛求疵……你可以在运行时重新解释;然后是变体和任何类型,您可以更改其类型。请参阅下面的答案。
  • @einpoklum 引用你自己的回答——“你就是不能这样。”

标签: c++ inheritance types declare


【解决方案1】:

如果您想保持流量不变,那么您只需将TestObj 设为std::shared_ptr&lt;Base&gt; 即可。这将使代码

Test(int a)
{
    std::shared_ptr<Base> TestObj;
    if (a==0)
    {
        TestObj = std::make_shared<DerivedA>();
    }
    else
    {
        TestObj = std::make_shared<DerivedB>(); 
    }

    TestObj->base = 7;

    if (a==0)
    {
        static_cast<DerivedA&>(*TestObj).x = 2; // need the cast so you can set the member
    }
    else
    {
        static_cast<DerivedB&>(*TestObj).y = 4; // need the cast so you can set the member
    }

    myObjs.push_back(TestObj);
}

【讨论】:

  • 不错的答案!大约在同一时间,我正在输入我的,并使它更流畅(也许)。
【解决方案2】:

“如何在不指定(在声明时)两个派生类中的哪一个将被使用的情况下声明一个变量?” - 你不能。

在 C++ 中,每个变量在声明时都必须有一个 single 类型。没办法。

但是,您可以使用指向基类的指针。这将接受分配任何派生类型,并可用于通过虚拟/动态调度调用派生类型中的函数。

【讨论】:

  • Jesper:可以使用 typedefs、TMP 等间接指定。
  • @einpoklum 任何变量仍然会以单一静态类型结束。
  • 是的,它会,但它仍然符合 OP 在修辞层面上的要求。
  • 谢谢大家。使用 std::shared_ptr TestObj;我现在还可以分配派生类型。稍后访问 TestObj(在类 Test 实例化之后)时,我仍然必须在尝试访问派生类的成员时使用 static_cast 技巧?或者有什么办法/更好的办法吗?
【解决方案3】:

我猜你需要这样的东西:

std::shared_ptr<Base> TestObj;
if (a==0)
{
    TestObj = std::make_shared<DerivedA>();
}
else
{
    TestObj = std::make_shared<DerivedB>();
}

TestObj->base = 7;

if (a==0)
{
    static_cast<DerivedA*>(TestObj.get())->x = 2;
}
else
{
    static_cast<DerivedB*>(TestObj.get())->y = 4;
}

myObjs.push_back(std::move(TestObj));

【讨论】:

  • 这是一个很好的答案!不过,总的来说,我会推荐 std::unique_ptr,除非有特定原因需要共享 onwership
【解决方案4】:

如果您愿意将Test 设为类模板,您可以根据a 的值选择对象类型。

template <int a>
class Test
{
   TypeSelector<a> TestObj;
   ...
};

在哪里

template <int a> class TypeSelectorHelper;

template <> class TypeSelectorHelper<0>
{
   using type = DerivedA;
}

template <> class TypeSelectorHelper<1>
{
   using type = DerivedB;
}

template <int a> 
using TypeSelector = typename TypeSelectorHelper<a>::type;

【讨论】:

    【解决方案5】:

    你可以让你的代码更简洁一点:

    class Test
    {
      public:
        Test(int a) {
            std::shared_ptr<Base> TestObj;
            if (a == 0) {
                std::shared_ptr<DerivedA> TestA  = std::make_shared<DerivedA>();
                TestA->x = 2;
                TestObj = TestA;
            }
            else {
                std::shared_ptr<DerivedB> TestB = std::make_shared<DerivedB>();
                TestB->y = 4;
                TestObj = TestB;
            }
            TestObj->base = 7;
            myObjs.push_back(TestObj);
        }
      private:
        vector<shared_ptr<Base>> myObjs;
    };
    

    【讨论】:

      【解决方案6】:

      你不能完全做你想做的事:声明一个变量意味着指定它的类型;如果您希望变量具有 DerivedA 类型或 DerivedB 类型,并在运行时做出决定 - 您就是不能这样做。

      但一切都没有丢失!

      如果你可以在编译时确定类型

      您可以在生成类型的编译器中基于元计算定义类型。这是@RSahu's answer:

      constexpr bool determine_if_we_need_derived_a() { /* ... compile-time computation ... */ }
      using type_i_need = typename type_selector<determine_if_we_need_derived_a()>::type;
      

      如果在编译时无法确定类型...

      ...但你知道它是 DerivedA 或 DerivedB 而已

      您可以使用std::variant:一个更漂亮、更安全、更好的 C 风格联合版本:

      std::variant<DerivedA, DerivedB> get_derived(/*params here*/)
      {
          // etc.
          if (condition) { return DerivedA( /* ... */); }
          else           { return DerivedB( /* ... */); }
      }
      
      // ...
      
      auto derived_object = get_derived(arg1, arg2, /* etc. */);
      

      但当然你之后需要使用visitation,以便根据derived_object 中的实际类型应用适当的操作。

      ...但你什么都不知道

      除了使用指针之外,您可能别无选择,就像@NathanOliver 和其他人建议的那样:

      std::unique_ptr<Base> get_derived(/*params here*/)
      {
          // etc.
          if (condition) { return std::make_unique<DerivedA>(/* ... */); }
          else           { return std::make_unique<DerivedB>(/* ... */); }
      }
      
      // ...
      
      myObjs.emplace_back(std::move(get_derived(arg1, arg2, /* etc. */)));
      

      ...你感觉很活泼

      你可以试试std::any。你可以把任何东西,任何类型的放进去!现在,它不是适合这项工作的抽象,但学习起来很有趣。问题是,您基本上需要知道 std::any 持有什么类型,然后才能检索并使用它。

      另一个想法是,不是存储指向值的指针,而是在您的 myObjs 中存储一个不透明的 lambda 对象(没有指针或任何东西)(这将成为 myObjActions 或其他东西),然后在必要时调用这些 lambdas。不过,所有这些 lambdas 都需要具有相同的类型! ...所以从某种意义上说,您只会将问题归咎于 lambda 中发生的事情。

      【讨论】:

      • @NeilButterworth:那么,你是赞成还是反对?如果是后者 - 愿意发表评论吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 2014-03-21
      • 2014-12-01
      • 2017-07-04
      • 2011-04-02
      • 1970-01-01
      相关资源
      最近更新 更多