简体   繁体   中英

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

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

Users is declared before with MyList<User*> Users; (MyList is a List ADT and I have a User class) and edges is declared with vector<string>edges

to what object is this error referring?

GMLwriter::write is not static function of GMLwriter, you need to call it through object. 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. 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.

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

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