简体   繁体   中英

compilation error C++ : can not call member function without object

I have the following main file where I tried to create a map with predefined value and pass it for further processing by other method. The main file is as is shown below :

int main(){
  map<id,Porto> _portoInit;

  id = 1;

  Porto p;
  p.val = 5;

  _portoInit.insert(pair<id, Porto>(id, p));

  Porto::setPorto(_portoInit);

  return 1;
}

where the setPorto is defined under a class as the following (in seperate file)

void Porto::setPorto( const map<id,Porto>&  _portoblock ) {
   //do stuffs
};

I got prompted with an error of "error: cannot call member function ... without object" Did not I declare the object of _portoInit in the main file already or it is a wrong way of declaration?

You need to invoke the method through the actual object:

p.setPorto(_portoInit);

Unless setPorto is a static method, your code is invalid.

setPorto is a non-static member function, so you need to call it on a Porto instance. For example:

p.setPorto(_portoInit);

Note that non-static member functions take an implicit first parameter of (possibly cv qualified) type T*, so you could have called it like this:

Porto::setPorto(&p, _portoInit);

In both cases, you need an object to call the member function on. This is what the compiler is telling you.

You should write

p.setPorto(_portoInit);

The "::" defines the scope of the function and is implicit in the above, as the object who's function is being called is a Porto.

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