2014-11-04 75 views
-3
#include<iostream> 

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

class derived : public base { 
    public: 
    void run(){}; 
    ~derived(); 
}; 

int main(){ 
    std::shared_ptr<base> b; 
    b.reset(new derived); 
    b->run(); 
} 

我有一个抽象基类和它的派生类。主要的是,我定义了一个共享指针,并将其与派生类型分配。然后,我使用虚拟功能。如果我注释掉b.reset(新派生),那么它工作正常。错误信息是任何人都知道为什么这段代码不能编译?

Undefined symbols for architecture x86_64: "derived::~derived()", referenced from: std::__1::shared_ptr::shared_ptr(derived*) in test-274b97.o std::__1::__shared_ptr_pointer, std::__1::allocator >::__on_zero_shared() in test-274b97.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

任何答案将不胜感激!
谢谢。

+8

你没有定义'derived ::〜derived()'。 – 0x499602D2 2014-11-04 17:26:55

+1

'base ::〜base()'也没有定义。 – 2014-11-04 17:31:01

+1

从技术上讲,它编译但不链接。是的,这是因为你声明了,但没有定义你的析构函数。 – 2014-11-04 17:31:52

回答

3

您没有为类base和派生类定义析构函数。你只是宣布他们。还有析构函数必须是虚拟的

+0

在他的具体情况下,析构函数不一定是虚拟的,尽管它通常是个好主意。 – 2014-11-04 17:35:28

+0

@MooingDuck:不,在这种情况下,它必须在'base'虚拟,因为存在多态删除('shared_ptr ')。 – 2014-11-04 17:36:26

+2

@FredLarson:通过'reset'设置'shared_ptr'的值存储给定的类型,在本例中为'derived *'。这里没有多态删除。如果它是'unique_ptr',那么你会是对的,但'shared_ptr'是魔术。 http://en.cppreference.com/w/cpp/memory/shared_ptr/reset“总是选择与提供的类型相对应的正确删除表达式,这就是使用单独参数Y将函数作为模板实现的原因。” – 2014-11-04 17:39:46

相关问题