无法在非成员函数中调用成员函数

时间:2019-09-23 07:16:33

标签: c++

我有一个类,它有一个成员函数,我想在一个非成员函数中调用该成员函数。

void mouseEvent(int evt, int x, int y, int flags, void* param);
class CMainClass
{

private:
// Xcoordinate of the click event
     int Xcoordinate;
public:
// Xcoordinate get method
         int CMainClass::GetXcoordinate()
         {
          return Xcoordinate;
         }

// Xcoordinate set method
         void CMainClass::SetXcoordinate(int newVal)
         {
           CMainClass::Xcoordinate = newVal;
         }

};


void mouseEvent(int evt, int x, int y, int flags, void* param)
{
      CMainClass::SetXcoordinate(x);

}

C ++非静态成员引用必须相对于特定对象

1 个答案:

答案 0 :(得分:0)

忽略与代码无关的问题,您在调用成员函数而不创建对象。

在mouseEvent中,您需要使用一个对象来调用SetXcoordinate。

void mouseEvent(int evt, int x, int y, int flags, void* param)
{
    //CMainClass obj();
    obj.SetXcoordinate(x);
}

如果在其他位置创建对象,则不必在同一函数中创建对象。