抽象类型对象的分配

Allocation of Abstract Type Object

我在这里读过这个帖子:

"Cannot allocate an object of abstract type" error

但我认为它没有回答我的问题...

我有文件:

base.h

#ifndef BASE_H
#define BASE_H

#include <iostream>

using namespace std;

class Base {

    public:

        Base(){
            protected_member = 0;
        }
        Base(int pm_val): protected_member(pm_val) {cout << "created Base." << endl;}
        virtual ~Base(){cout << "deleted Base." << endl;}

        virtual int access_Base_pm() = 0;

    protected:

        int protected_member;

};

#endif

base.cpp(我猜是多余的)

#include "base.h"
#include "derived.h"

derived.h

#ifndef DERIVED_H
#define DERIVED_H

#include <iostream>
#include "base.h"

using namespace std;

class Base;

class Derived: public Base {

    public:

        Derived(){cout << "created Derived." << endl;}
        ~Derived(){cout << "deleted Derived." << endl;}

        int access_Base_pm();

};

#endif

derived.cpp

#include "derived.h"
#include "base.h"

int Derived::access_Base_pm(){
    return protected_member;
}

当我运行

main_1.cpp

#include <iostream>
#include "base.h"
#include "derived.h"

using namespace std;

int main(){

    Base* base;
    base = new Derived();
    cout << base->access_Base_pm() << endl;

}

一切似乎都很好。

但是当我运行

main_2.cpp

#include <iostream>
#include "base.h"
#include "derived.h"

using namespace std;

int main(){

    Base* base = new Base;
    base = new Derived();
    cout << base->access_Base_pm() << endl;

}

main_3.cpp

#include <iostream>
#include "base.h"
#include "derived.h"

using namespace std;

int main(){

    Base(5)* base;
    base = new Derived();
    cout << base->access_Base_pm() << endl;

}

我得到"error: cannot allocate an object of abstract type ‘Base’"

为什么?我不明白。正如它在另一个线程中所说的那样,我只能通过指针访问对象......我错过了什么?

您不能对 Base 进行 new,因为它是抽象类型。

Base* base = new Base;

是非法的

Base* base = new Derived();

可以,但出于此处解释的原因:Is no parentheses on a constructor with no arguments a language standard? 我更喜欢:

base = new Derived;

我也不知道这是否编译:

Base(5)* base;

您发表该声明的意图是什么? 根据您的评论,它应该是

Base* base = new Base(5);

Base base(5); 

如果不需要指针,但这将不起作用,因为 Base 是抽象的。 我不能用 Derived 来做,因为 Derived 缺少一个带参数的构造函数。所以你需要:

class Derived: public Base {

public:

    Derived(){cout << "created Derived." << endl;}
    Derived(){cout << "created Derived." << endl;}
    ~Derived(int pm_val):Base(pm_val){cout << "deleted Derived." << endl;}

    int access_Base_pm();

};

Base* base = new Derived(5);

Derived derived(5);
Base* base = &derived;

main_1.cpp 看起来不错,因为它很好。

main_2.cpp 做了一些相当有趣的事情

Base(5) * base;

现在,如果 Base(5) 某种类型——它不是——这将是指针变量的声明。但是,Base(5) 实际上是一个临时变量(它与名称为 base 的对象相乘,而该对象在您的代码中甚至不存在),通过构造类型为 Base 的变量创建,并且将其构造函数传递给 5。这正是您链接的问题解释为禁止的内容。

main_3.cpp 公然做 new Base 这正是您链接的问题所探讨的 - Base 是抽象的,您尝试创建该类型的对象。