gpt4 book ai didi

c++ - std::shared_ptr 和继承

转载 作者:IT老高 更新时间:2023-10-28 22:41:00 36 4
gpt4 key购买 nike

我在继承类的 shared_ptr 之间的自动类型转换方面遇到了一些问题。

我的类结构如下,一个基类Base和两个派生类Derived1Derived2

// Base class
class Base {
protected:
...
...
public:
Base() = default;
virtual ~Base() = default;
virtual void run() = 0;
...
...
};

// Derived class
class Derived1: Base {
protected:
...
...
public:
Derived1() = default;
virtual ~Derived1() = default;
void run() {...}
...
...
};

// Derived class
class Derived2: Base {
protected:
...
...
public:
Derived2() = default;
virtual ~Derived2() = default;
void run() {...}
...
...
};

我有一个函数doSomething()

void doSomething(std::shared_ptr<Base> ptr) {
ptr->run();
...
}

我像这样用派生类调用函数-

doSomething(make_shared<Derived1>())
doSomething(make_shared<Derived2>())

但我收到一条错误消息 -

no viable conversion from 'shared_ptr<class Derived1>' to 'shared_ptr<class Base>'
no viable conversion from 'shared_ptr<class Derived1>' to 'shared_ptr<class Base>'

我做错了什么?仅将 static_pointer_cast 用于 Base 类型是否安全?喜欢-

doSomething(static_pointer_cast<Base>(make_sahred<Derived2>()))

解决方案我的错...问题是我私下继承了基类。

最佳答案

据我所知,您提供的代码编译良好:http://ideone.com/06RB2W

#include <memory>

class Base {
public:
Base() = default;
virtual ~Base() = default;
virtual void run() = 0;
};

class Derived1: public Base {
public:
Derived1() = default;
virtual ~Derived1() = default;
void run() {}
};

class Derived2: public Base {
public:
Derived2() = default;
virtual ~Derived2() = default;
void run() {}
};

void doSomething(std::shared_ptr<Base> ptr) {
ptr->run();
}

int main() {
doSomething(std::make_shared<Derived1>());
doSomething(std::make_shared<Derived2>());
}

关于c++ - std::shared_ptr 和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24603307/

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