如何在具有多态性的函数外部创建对象
How to create objects outside functions with polymorphism?
我想使用多态性并在main或任何其他函数之外创建对象,以便函数独立于我拥有的对象类型。我的代码如下:
主类:
class load{ //Main class
protected:
static load **L;
static int n, n1;
public:
load(){};
virtual float getpower()=0;
static int getn();
static load ** getL();
};
load **load::L;
int load::n;
int load::n1;
int load::getn(){
return n;
}
load** load::getL(){
return L;
}
子班:
class load1:public load{
private:
float power;
public:
load1();
load1(int s);
void createUnits1();
float getpower();
}l1(0); //Object creation
load1::load1(int s){
createUnits1();
}
void load1::createUnits1(){
cout<<"Give the number of type 1 objects: "<<endl;
cin>>n1;
for (int i=0;i<n1;i++){
load1 temp; //Run default constructor
}
}
load1::load1(){
cout<<"Give the power of the device: "<<endl;
cin>>power;
n++;
if (n==1){
L=(load **)malloc(n*sizeof(load *));
}
else {
L=(load **)realloc(L,n*sizeof(load *));
}
L[n-1]=this;
}
float load1::getpower(){
return power;
}
计算功能:
float get_total_P(load **l, int num){
float tot_power=0;
for(int i=0;i<num;i++){
tot_power+=l[i]->getpower();
}
return tot_power;
}
我的主要功能:
int main() {
load **l;
int num;
num=load::getn();
l=load::getL();
float total_P=get_total_P(l, num);
cout<<total_P;
return 0;
}
上面的代码产生了分段错误,但我看不出原因。分段故障在线
tot_power+=l[i]->getpower();
所以我想我创建对象的方式是错误的。有没有更好的方法可以做到这一点?
你的段错误的原因,是l
没有指向任何有效的东西!
在main()
中,您可以使用 load::getL()
初始化l
。 但是此函数仅返回具有相同类型且在负载类中定义为静态但从未初始化的load::L
。
你已经在派生类中编码load1
了一些L
初始化代码,但它从未在main()
中被调用。
您的代码还存在一些严重的设计问题:
-
不建议在C++代码中使用
malloc()
和realloc()
。 如果在 中创建对象C++请使用new
. 如果你想要一些动态数组,请使用向量。 -
您可以在调用
getL()
之前创建一些load1
对象,则可以获得L
,因此l
初始化。 但是由于您的 realloc,如果您在调用get_total()
之前创建任何其他load1
对象,那么 l 将冒着指向一个过时的无效地址的风险。 -
在构造函数中请求用户输入是一种糟糕的做法和糟糕的设计。 构造函数旨在使用您在调用他时给他的参数对对象进行cosntruc。 想象一下,用户会给出一个无效的参数? 每当构建
load1
对象时,都会要求用户输入。 即使对于临时变量,当您编写 load1 a[10] 时,甚至不会从效果说话;
相关文章:
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- C++:函数外部的超时功能
- 如何在函数外部访问函数中局部变量的值?
- 在成员函数外部封闭类的定义中需要默认成员初始值设定项
- 以延长构造函数外部 QT 对象的生存期
- 全局静态变量不"staying defined"函数外部
- C++ 函数外部丢失的指针对象
- 向量大小在构造函数外部恢复为 0
- 删除函数外部的实例化对象
- 在函数外部编写代码
- 为什么我不能添加到方法/函数外部的 ostringstream
- 用于在方法或函数外部声明的变量的内存
- SDL2 在函数外部加载字体会引发错误
- 如何在具有多态性的函数外部创建对象
- 在函数外部声明对象,将其作为引用传递,然后在函数内部创建它
- 向量未在函数C++外部更新
- 访问函数外部的堆栈对象
- 在c++中访问函数外部的数组
- 如何更新函数外部的数组(指向指针)