抽象类型对象的分配
Allocation of Abstract Type Object
我在这里阅读了这个线程:
"无法分配抽象类型的对象"错误
但我认为它不能回答我的情况...
我有文件:
碱基.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
是抽象的,您尝试创建该类型的对象。
相关文章:
- 使用操作重载对象重新分配对象
- 静态分配对象的值初始化
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 堆分配对象中的堆栈对象在 c++ 中在哪里分配?
- 在 c++ 的构造函数中分配对象向量时出错
- 动态分配对象中的字段-动态分配更好还是静态分配更好?C++
- 操作后通过运算符分配对象
- 如何捕获源自静态分配对象的构造函数的异常?
- 在C++中,当重新分配对象时,为什么构造函数在析构函数之前触发?
- 如何使用每个对象的单个构造函数参数动态分配C++对象数组?
- 将动态分配对象传递到 boost::any 构造函数中
- 混合指向已分配对象和作用域对象的指针
- C 删除指向动态分配对象的指针
- 有关动态分配对象的问题
- 类的堆分配对象是否在其作用域之后但在 C++ 中调用其析构函数之前处于活动状态
- C++ 中的黑白堆分配对象和堆栈分配对象的性能差异
- 是隐式创建的默认构造函数,负责分配对象内存
- 如何删除用于动态分配对象的智能指针
- 分配对象数组时如何初始化每个对象
- 用于堆栈分配对象的C++虚拟析构函数内联