我收到编译错误
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是List ADT,我有一个User类),边缘声明为vector<string>edges
这个错误指的是object
?
答案 0 :(得分:18)
GMLwriter::write
不是GMLwriter的静态函数,需要通过对象调用它。例如:
GMLwriter gml_writer;
gml_writer.write(argv[3], Users, edges);
如果GMLwriter::write
不依赖于任何GMLwriter状态(访问GMLwriter
的任何成员),则可以使其成为静态成员函数。然后你可以直接调用它而不用对象:
class GMLwriter
{
public:
static bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
^^^^
};
然后你可以打电话:
GMLwriter::write(argv[3], Users, edges);
答案 1 :(得分:1)
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);
答案 2 :(得分:0)