简体   繁体   English

编译错误C ++:无法在没有对象的情况下调用成员函数

[英]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) 其中setPorto在类下定义如下(在单独的文件中)

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? 我收到错误提示“错误:无法调用成员函数...没有对象”我是不是已经在主文件中声明了_portoInit的对象,或者它是一种错误的声明方式?

You need to invoke the method through the actual object: 您需要通过实际对象调用该方法:

p.setPorto(_portoInit);

Unless setPorto is a static method, your code is invalid. 除非setPortostatic方法,否则您的代码无效。

setPorto is a non-static member function, so you need to call it on a Porto instance. setPorto是一个非静态成员函数,因此您需要在Porto实例上调用它。 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: 请注意,非静态成员函数采用隐式的第一个参数(可能是cv限定的)类型T *,因此您可以像这样调用它:

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. “::”定义了函数的范围,并且隐含在上面,因为调用函数的对象是Porto。

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

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