Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用基类智能指针重载函数_C++_Oop_Inheritance_Overloading - Fatal编程技术网

C++ 使用基类智能指针重载函数

C++ 使用基类智能指针重载函数,c++,oop,inheritance,overloading,C++,Oop,Inheritance,Overloading,我有3个类:第一个是纯虚拟基类base,带有派生类derived1,derived2 第二个foo将智能ptr保存到基类 第三个包含一个到foo的智能ptr,并有一个重载成员函数,我想依赖于foo中ptr指向的派生类 这是工作代码 #include<iostream> #include<boost/shared_ptr.hpp> using namespace std; class base{ public: base(){} ~base(){}

我有3个类:第一个是纯虚拟基类
base
,带有派生类
derived1
derived2

第二个
foo
将智能ptr保存到基类

第三个包含一个到
foo
的智能ptr,并有一个重载成员函数,我想依赖于foo中ptr指向的派生类

这是工作代码

#include<iostream>
#include<boost/shared_ptr.hpp>

using namespace std;

class base{
public:
    base(){}
    ~base(){}
    virtual void FuncDer()=0;
};

class derived1 : public base{
    derived1(){}
    virtual void FuncDer(){
    cout<<"derived function1!"<<endl;
    }
};

class derived2 : public base{
    derived2(){}
    virtual void FuncDer(){
        cout<<"derived function2!"<<endl;
}
};

class foo {
public:
   foo();
    ~foo();
    boost::shared_ptr<base> get_base_ptr(){
        return base_obj;
    }
private:
    boost::shared_ptr<base> base_obj;
};

class bar {
public:
    bar();
    ~bar();
    void callfunc(){
    func(foo_ptr->get_base_ptr());
    }
private:
    boost::shared_ptr<foo> foo_ptr;
    void func(boost::shared_ptr<derived1>);
    void func(boost::shared_ptr<derived2>);
};


int main()
{
    cout<<"test"<<endl;

    return 0;
}
#包括
#包括
使用名称空间std;
阶级基础{
公众:
base(){}
~base(){}
虚拟void functder()=0;
};
类derived1:公共基{
derived1(){}
虚空函数(){

cout原则上这是正确的方法:在基上调用函数,多态性将做正确的事情

但是,您的代码无法编译:bar中的
func
定义无效(至少我不确定您的目的是什么-它们应该实现什么?),并且
callfunc
中的func调用两次取消引用指针


如果您需要具体的修复,请给出确切的错误。

foo::get_base_ptr
返回
shared_ptr
,并且
base
不能用作任何重载函数的参数
bar::func
。代码目前不允许多态性做正确的事情,必须进行重构。哦,等等,我想现在我理解了其目的是:根据对象类调用func的不同重载?在这种情况下,是的,重构:理想情况下,在派生类中应该做什么,只调用基函数。将功能从func(derived1)移动到FuncDer()在derived1中,黑客的方法是检查所有派生类的
dynamic\u cast
s。使用不同的实现在两个派生对象中移动
func()
。然后调用
foo\u ptr->func()
callfunc
中的
是否可以在以类对象
bar
为参数的派生类中增加虚拟函数,并将
bar::func
函数更改为公共函数?很抱歉,延迟了,我到目前为止还没有机会看到这个问题。我现在发布了重现错误的工作代码。