在C ++中从指针向量访问子类变量到超类

本·林赛

如果我有一个指向超类的指针的向量,并将一个子类的成员添加到该向量,则可以很好地调用子类函数,但是由于我的代码是当前的代码,所以我无法访问该子类唯一的变量。我如何B从一个指针进入vec

#include <iostream>
#include <vector>

class Super {
  public:
    int A;
    Super(int a) : A(a) {}
    virtual void foo() = 0;
};

class Sub : public Super {
  public:
    int B;
    Sub(int a, int b) : Super(a), B(b) {}
    void foo() {
      std::cout << "calling foo from Sub\n";
    }   
};

int main() {
  std::vector<Super*> vec;
  vec.push_back(new Sub(2, 3));
  vec[0]->foo();                                // No problem
  std::cout << "A: " << vec[0]->A << std::endl; // No problem
  std::cout << "B: " << vec[0]->B << std::endl; // Compile Error
}
轨道轻度竞赛

您可以用dynamic_cast<Sub*>(,甚至static_cast<Sub*>可以保证每个指针都指向)来天真地解决此问题,Sub但是…不要!这是用于虚拟调度的教科书箱。

我要添加一个virtual void print(std::ostream&),它是整个继承层次结构的接口一部分,以及operator<<可以在该层次结构内的任何类型的对象上调用的一个。让C ++运行时多态性的神奇和功能覆盖做到这一切给你,所以main并不需要了解之间的差异A或者B还是什么成员变量每个人都有,也没有弄清楚是哪种对象的每个指针实际上指向。

您还应该存储一个智能指针,以避免内存泄漏。

#include <iostream>
#include <vector>
#include <memory>

struct Super {
    int A;
    Super(int a) : A(a) {}

    virtual void foo() = 0;
    virtual void print(std::ostream& os) const
    {
        os << "A: " << A << '\n';
    };
};

struct Sub : Super {
    int B;

    Sub(int a, int b) : Super(a), B(b) {}

    void foo() { std::cout << "calling foo from Sub\n"; }
    virtual void print(std::ostream& os) const
    {
        Super::print(os);
        os << "B: " << B << '\n';
    }
};

std::ostream& operator<<(std::ostream& os, const Super& obj)
{
    obj.print(os);
    return os;
}

int main()
{
   std::vector<std::unique_ptr<Super>> vec;
   vec.emplace_back(std::make_unique<Sub>(2, 3));
   vec[0]->foo();
   std::cout << *(vec[0]);
}

现场演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章