如何在具有多态性的函数外部创建对象

How to create objects outside functions with polymorphism?

本文关键字:函数 外部 创建对象 多态性      更新时间:2023-10-16

我想使用多态性并在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] 时,甚至不会从效果说话;