简体   繁体   中英

undefined reference to `Init::b'

I have class here

#include<cstdlib>
#include<time.h>

    struct between{
    double min;
    double max;
};

class Init{



public:
    static const int args=2;
    static between* b;

    static double function(double i[]){
        return abs(i[0]*i[1]);
        return (25*i[0]*i[0]-5*i[0]+3);
    }

    static double abs(double d){
        return (d>0?d:-d);
    }

};

and class which includes:

#include "Init.cpp"
#include<iostream>

using namespace std;
class Chunk{
public:
    double values[Init::args];
    double res;
    static Chunk* sex(Chunk* c1,Chunk* c2){
        Chunk* c=new Chunk();
        for(int a=0;a<Init::args;a++){
            double t=getRand();
            c->values[a]=c1->values[a]*t+c2->values[a]*(1.0-t);
        }
        return c;

    }

    static double getRand(){
        double d=rand()/(double)RAND_MAX;
        return d;
    }

    double getResult(){

        res=Init::function(values);
    }

    static Chunk* generateChunk(){
    Chunk* c=new Chunk();
        for(int a=0;a<Init::args;a++){
            double t=getRand();
            c->values[a]=Init::b[a].min*t+Init::b[a].max*(1.0-t);//ERROR HERE!
        }
    return c;
    }

};

And I get error:

/home/oneat/NetBeansProjects/wearethechampions/Chunk.cpp:33: undefined reference to `Init::b'

Any idea why?

Error is caused by undefined static variable in class Init .

You declare two such variables:

static const int args = 2;

This is declaration and in-class initialization - constant integers are allowed to be initialized inside class body. Such members does not require additional definition, unless you want to use them as lvalue .

static between* b;

This is only declaration , b doesn't get defined anywhere. In source file ( .cpp ), that contains definition of methods belonging to Init class, add following line (you usually want to zero-initialize all pointers):

between* Init::b = NULL; //In pre-C++11 code

or

between* Init::b = nullptr; //In C++11-compliant code

You need to add in a CPP file :

between* Init::b = NULL ; 

You defined b in the header, but you don't have the body of the static object defined in any object.

EDIT (since you have .cpp files only)

Define the b value outside your class .

Meaning, after the Init class declaration,add the line :

between* Init::b=NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM