[英]Error - cannot call member function without object in C++
我收到编译错误
cannot call member function 'bool GMLwriter::write(const char*, MyList<User*>&, std::vector<std::basic_string<char> >)' without object
当我尝试编译时
class GMLwriter{
public:
bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
};
该函数稍后定义,并在main
使用
GMLwriter::write(argv[3], Users, edges);
使用MyList<User*> Users;
声明MyList<User*> Users;
(MyList是一个列表ADT,我有一个User类),并且用vector<string>edges
声明了vector<string>edges
该错误指的是什么object
?
GMLwriter::write
不是GMLwriter的静态函数,您需要通过对象调用它。 例如:
GMLwriter gml_writer;
gml_writer.write(argv[3], Users, edges);
如果GMLwriter::write
不依赖于任何GMLwriter状态(访问GMLwriter
任何成员),则可以将其GMLwriter
静态成员函数。 然后,您可以直接调用它而无需对象:
class GMLwriter
{
public:
static bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
^^^^
};
那么您可以致电:
GMLwriter::write(argv[3], Users, edges);
GMLwriter
不是对象,而是类类型。
调用成员函数需要一个对象实例,即:
GMLwriter foo;
foo.write(argv[3], Users, edges);
尽管您很有可能希望该函数为自由或静态:
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);
要么
bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
// ...
write(argv[3], Users, edges);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.