抽象类型对象的分配

Allocation of Abstract Type Object

本文关键字:分配 对象 类型 抽象类 抽象      更新时间:2023-10-16

我在这里阅读了这个线程:

"无法分配抽象类型的对象"错误

但我认为它不能回答我的情况...

我有文件:

碱基.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

基地.cpp(我猜是多余的(

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

派生.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

派生.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;
}

我收到"错误:无法分配抽象类型'Base'的对象">

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

你不能做一个新的 Base ,因为它是抽象类型。

Base* base = new Base;

是非法的

Base* base = new Derived();

是可以的,但出于这里解释的原因:没有参数的构造函数上没有括号是语言标准吗?我更喜欢:

base = new Derived;

我也不知道这是否编译:

Base(5)* base;

你这句话的意图是什么?根据您的评论,它应该是

Base* base = new Base(5);

Base base(5); 

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

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是抽象的,您尝试创建该类型的对象。