简体   繁体   English

声明和初始化问题

[英]Problems with declarations and initializations

I am trying to rewrite a code I have written earlier. 我正在尝试重写我之前编写的代码。 The code uses cplex concert API; 该代码使用cplex Concert API;

#include <ilcplex/ilocplex.h>
    using namespace std;
    ILOSTLBEGIN

    int main(){

    IloEnv env;
    IloModel model(env);
    IloVarArray x(env);
    IloCplex cplex(model);

    return 0;
    }

This code (though it doesn't do anything) works... However now i have implemented my own Class and would like to be able to use these functions as well but I don't know how to inizialize them. 这段代码(尽管它什么都不做)可以工作...但是,现在我已经实现了自己的类,也希望能够使用这些函数,但是我不知道如何将其初始化。 So this time I have written them in a differnet class called solver. 因此,这次我将它们编写在一个名为Solver的differentnet类中。

    //solver.h
    #ifndef solver_h
    #define solver_h
    #include <ilcplex/ilocplex.h>
    class solver{
    public:
        IloModel model;
     IloNumVarArray x;
     IloRangeArray con;
     IloCplex cplex;
     solver();
    solver~();

    };

#endif

Then the cpp file 然后是cpp文件

//solver.cpp
    #include <ilcplex/ilocplex.h>
    #include <vector>
    using namespace std;
    #include "solver.h"
    ILOSTLBEGIN
    solver::solver(){
    IloEnv env;
    IloModel model(env);
    IloVarArray x(env);
    IloCplex cplex(model);
    }

If i add a function to this class eg a function that calls x.add(IloNumVar(env)); 如果我向此类添加函数,例如,调用x.add(IloNumVar(env))的函数; In the first example this would add an variable to the x(array), but when I have it in a different class I catch "tring to implement empty handle"... 在第一个示例中,这将向x(array)添加一个变量,但是当我在另一个类中使用它时,我捕捉到“试图实现空句柄”。

I know I'm doing everything right in the main program, and I also get it to work if I dont have the different Cplex classes in the h.file but then I can only use the same model once and i would want to call the same model several times. 我知道我在主程序中所做的一切正确,而且如果我在h.file中没有不同的Cplex类,我也可以使它正常工作,但是我只能使用相同的模型一次,所以我想调用相同的模型几次。

Is there something clearly wrong here (Besides the lack of code, destructors, etc...) in the h.file or? h.file中是否存在明显的错误(除了缺少代码,析构函数等),还是?

This code: 这段代码:

solver::solver(){
   IloEnv env;
   IloModel model(env);
   IloVarArray x(env);
   IloCplex cplex(model);
}

is not initialising your class members - it is creating local variables in the constructor, which will destroyed when the constructor exits. 并未初始化您的类成员-而是在构造函数中创建局部变量,该局部变量在构造函数退出时将被销毁。 You want something like: 您想要类似的东西:

solver :: solver( IloEnv & env )
      : model( env ), x( env ), cplex( model ) {
}

then in main: 然后在主要:

int main() {
    IloEnv env;
    solver s( env ); // create solver object
}

Perhaps 也许

solver::solver () : model (env), x (env), cplex (model)
{
}

is closer to what you want. 更接近您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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