简体   繁体   English

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

[英]Error - cannot call member function without object in C++

I get the compile error 我收到编译错误

cannot call member function 'bool GMLwriter::write(const char*, MyList<User*>&, std::vector<std::basic_string<char> >)' without object

when I try to compile 当我尝试编译时

 class GMLwriter{
    public:
    bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
};

the function is defined later and called in main with 该函数稍后定义,并在main使用

GMLwriter::write(argv[3], Users, edges);

Users is declared before with MyList<User*> Users; 使用MyList<User*> Users;声明MyList<User*> Users; (MyList is a List ADT and I have a User class) and edges is declared with vector<string>edges (MyList是一个列表ADT,我有一个User类),并且用vector<string>edges声明了vector<string>edges

to what object is this error referring? 该错误指的是什么object

GMLwriter::write is not static function of GMLwriter, you need to call it through object. GMLwriter::write不是GMLwriter的静态函数,您需要通过对象调用它。 For example: 例如:

GMLwriter gml_writer;   
gml_writer.write(argv[3], Users, edges);

If GMLwriter::write doesn't depend on any GMLwriter state(access any member of GMLwriter ), you can make it a static member function. 如果GMLwriter::write不依赖于任何GMLwriter状态(访问GMLwriter任何成员),则可以将其GMLwriter静态成员函数。 Then you could call it directly without object: 然后,您可以直接调用它而无需对象:

class GMLwriter
{
public:
   static bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
   ^^^^
};

then you could call: 那么您可以致电:

GMLwriter::write(argv[3], Users, edges);

GMLwriter is not an object, it's a class type. GMLwriter不是对象,而是类类型。

Calling member functions requires an object instance, ie: 调用成员函数需要一个对象实例,即:

GMLwriter foo;   
foo.write(argv[3], Users, edges);

Although there's a good chance you intended the function to be free or static: 尽管您很有可能希望该函数为自由或静态:

class GMLwriter{
    public:
    // static member functions don't use an object of the class,
    // they are just free functions inside the class scope
    static bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
};

// ...
GMLwriter::write(argv[3], Users, edges);

or 要么

bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
// ...
write(argv[3], Users, edges);

You might be trying to call / create a static method, to be 您可能正在尝试调用/创建静态方法,

In this case, you might want to precede your declaration with a 'static' modifier. 在这种情况下,您可能需要在声明之前加上“静态”修饰符。

http://www.functionx.com/cppcli/classes/Lesson12b.htm http://www.functionx.com/cppcli/classes/Lesson12b.htm

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

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