如何使用多态创建函数外的对象?

时间:2014-12-06 12:52:43

标签: c++ class inheritance 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();

所以我想我创建对象的方式是错误的。有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

你的段错误的原因是,l并未指出任何有效的内容!

main()中,您使用l初始化load::getL()。但是此函数仅返回具有相同类型的load::L,并且在您的加载类中定义为静态但从未初始化。

您已在派生类load1中编写了L的一些初始化代码,但它永远不会在main()中进行调用。

您的代码也存在一些严重的设计问题:

  • 建议不要在C ++代码中使用malloc()realloc()。如果在C ++中创建对象,请使用new。如果您想要一些动态数组,请使用vectors

  • 如果您在调用L之前创建了一些l个对象,则可以load1并因此getL()初始化。但是由于你的realloc,如果你在调用load1之前创建任何其他get_total()对象,那么我将冒险指向一个过时的无效地址。

  • 在构造函数中请求用户输入是不好的做法和糟糕的设计。构造函数用于在您调用它时使用您给出的参数来构造对象。想象一下,用户会给出一个无效的参数?每当构造load1对象时,将要求用户输入。即使对于临时变量,甚至在写入load1 a [10]时也没有说出效果;

相关问题