没有类型转换的模板化派生类的 C++ 访问成员

标签 c++ vector smart-pointers derived-class

是否可以使用指向基类的指针访问派生类的成员?

// Example program
#include <iostream>
#include <vector>
#include <memory>
#include <string>

class A {
    public:
    std::string x = "this is the wrong x\n";
    };

template <class T>
class B : public A {
    public:
    T x;
    };

int main()
{
    std::vector<std::unique_ptr<A>> vector;
    auto i = std::make_unique<B<int>>();
    i->x = 6;
    vector.push_back(std::move(i));
    for(auto &element : vector){
        std::cout << element->x;
    }
}

在这里,我总是从类 A 中获取输出。我无法对其进行类型转换,因为我事先不知道该元素是类型 A 还是类型 B。有没有正确的方法来做到这一点?

最佳答案

正确的方法是制作一个虚拟函数来执行打印等任务。

class A {
public:
    std::string x = "this is the wrong x\n";
    virtual ~A() = default;
    virtual void print() const { std::cout << x; }
};

template <class T>
class B : public A {
public:
    T x;
    virtual void print() const override { std::cout << x; }
};

int main()
{
    std::vector<std::unique_ptr<A>> vector;
    auto i = std::make_unique<B<int>>();
    i->x = 6;
    vector.push_back(std::move(i));
    for(auto &element : vector){
        element->print();
    }
}

关于没有类型转换的模板化派生类的 C++ 访问成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51982711/

相关文章:

c++ - 是否需要 std::launch::async 策略?

vector - 试图在Rc <RefCell <... >>内部修改 future Vec

vector - 如何在 PyQGIS 中向地理包追加/添加图层

c++ - 如何用android ndk和eclipse编译c++11代码?

c++ - 不同的智能指针可以引用同一个对象吗?

c++ - 如何在 C++ 中的 .so 文件中包含一个库

c++ - 包含头文件时,路径是否区分大小写?

c++ - Winapi 定时器回调线程,永不返回

matlab - 在 Octave 中加载输入文件并创建向量和矩阵

c++ - 是否有可以配置为在销毁时不删除的 boost 智能指针类?