Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/14.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++ clang诊断错误-分配抽象类类型为';基数'; #包括 #包括 使用名称空间std; 阶级基础 { 公众: 虚拟void foo()=0; 受保护的: int num{1}; 公众: Base(){ cout_C++_C++17 - Fatal编程技术网

C++ clang诊断错误-分配抽象类类型为';基数'; #包括 #包括 使用名称空间std; 阶级基础 { 公众: 虚拟void foo()=0; 受保护的: int num{1}; 公众: Base(){ cout

C++ clang诊断错误-分配抽象类类型为';基数'; #包括 #包括 使用名称空间std; 阶级基础 { 公众: 虚拟void foo()=0; 受保护的: int num{1}; 公众: Base(){ cout,c++,c++17,C++,C++17,在main()函数中,执行以下操作: unique_ptr b(新派生()); 这是因为std::make_unique()接受实际的构造函数参数。多态性无法做到这一点,但直接使用堆分配的资源实例化std::unique_ptr并没有错 确实更喜欢std::make_unique()这是有意义的。但这不是其中一种情况。请适当地格式化代码,Prapeer。make_unique不会在智能指针中使用指向您要粘贴的对象的指针。它使用实际的构造函数参数。因此,它想要创建基。但它不能,因为Base是抽象的

main()
函数中,执行以下操作:
unique_ptr b(新派生());

这是因为
std::make_unique()
接受实际的构造函数参数。多态性无法做到这一点,但直接使用堆分配的资源实例化
std::unique_ptr
并没有错


确实更喜欢
std::make_unique()
这是有意义的。但这不是其中一种情况。

请适当地格式化代码,Prapeer。
make_unique
不会在智能指针中使用指向您要粘贴的对象的指针。它使用实际的构造函数参数。因此,它想要创建
。但它不能,因为
Base是抽象的。这里的解决方案不是编写
Base::foo()
,而是做正确的事情:只要调用
unique\u ptr
的构造函数,给定指向
派生的
的指针
make\u unique
创建类型为
T
的唯一拥有的新对象。它不拥有现有对象的所有权。(它是“make”)就像“给我做比萨饼”,而不是“让我成为百万富翁”。)
#include <iostream>
#include <memory>

using namespace std;

class Base
{
public:
    virtual void foo() = 0;
protected:
    int num{ 1 };

public:
    Base() {
        cout << "Base class constructor" << endl;
    }
     virtual ~Base() 
    {
        cout << "Base class destructor " << endl;
    }
private:
};

class Derive : public Base {
public:
    Derive() {
        cout << "Derive class constructor" << endl;
    }
    ~Derive() {
        cout << "Derive class destructor " << endl;
    }
public:
    void foo() override{
        cout << "Derive class Foo function" << endl;
    }
};

int main() {
    unique_ptr<Base> b = make_unique<Base>(new Derive());
    b->foo();   
}