我在这里读过这个帖子:
"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(我认为是redudant)
#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;
}
我得到“错误:无法分配抽象类型的对象'Base'”
为什么呢?我不明白。正如在另一个帖子中所说的那样,我只是通过一个指针来访问对象......我错过了什么?
答案 0 :(得分:0)
你不能做新的Base因为它是抽象类型。
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;
答案 1 :(得分:0)
main_1.cpp看起来很好,因为它很好。
main_2.cpp做了一件非常有趣的事情
Base(5) * base;
现在,如果Base(5)
某种类型 - 它不是 - 这将是一个指针变量的声明。但是,Base(5)
实际上是一个临时变量(与一个名称为base
的对象相乘,在您的代码中甚至不存在),通过构造Base
类型的变量来创建传递它的构造函数5
。这正是你所链接的问题解释为禁止的。
main_3.cpp公然执行new Base
这正是您所链接的问题探讨的内容 - Base
是抽象的,您尝试创建该类型的对象。