开发者

Problem declaring Global Variable in C++

开发者 https://www.devze.com 2023-02-07 21:52 出处:网络
I have a global variable in th开发者_开发知识库e class: IloModel model; that is going to be shared amongst several functions of the class.

I have a global variable in th开发者_开发知识库e class:

IloModel model;

that is going to be shared amongst several functions of the class.

In one of the functions, I am going to initialize this model like:

model(env);

I get the error: Error 1 error C2064: term does not evaluate to a function taking 1 arguments

This works if I write in the function:

IEnv env;
IloModel model(env);

but not if the model object is declared globally.

Please advice how to make model object global so same object can be shared amongst several functions?


when you do

IloModel model;

It is being initialised with the default constructor; so IloModel()

What you need to do is

model = IloModel(env);

There error is probably because it is looking for a function model with one paramatere and not finding one.


Not sure I understand what you mean with "global" because it seems you're talking about a member of the class. Anyway if your data is copyable you can do

model = IloModel(env);

this will create a new model and copy it over the current one.


Why don't you declare env globally also and then directly initialize model with env? In other words, put this globally:

IEnv env;
IloModel model(env);

Otherwise, you cannot call the constructor to initialize model, you need another init method on IloModel class to specify the IEnv after the construction.


You can not call the constructor of model of object at a later point of time. You need to do it at the time of definition of the object itself. If env is also global then you can do IModel model(env).


The function you are calling on the model class, is it's constructor. As a member of your class (global to the class, but certainly not the application unless it is static and accessible), you get to construct it once and that is in the initializer-list of the class that has it, e.g:

class MyClass
{
private:
    IloModel model;

public:
     MyClass(IEnv _env) : model(_env) // constructs model here, passing env
     {
     };

     void someFunction()
     {
         // use model here
     };
}; // eo class MyClass

Now, I do not know what IEnv is at all (or the model for that matter) so this might not work for you if the logic dictates that you need to construct model with a different IEnv each time you use it.


In your last example, you call the constructor, a special function to initialize the object. The first example tries to call the operator() on your object model, and if the class IloModel does not define one, it doesn't exist.

You could, however, call IloModel(env); which would create an temporary object and immediately destroy it again, heh.

0

精彩评论

暂无评论...
验证码 换一张
取 消