错误 - 无法在 C++ 中调用没有对象的成员函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14805878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error - cannot call member function without object in C++
提问by user2059901
I get the compile error
我收到编译错误
cannot call member function ‘bool GMLwriter::write(const char*, MyList<User*>&, std::vector<std::basic_string<char> >)' without object
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);
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
用户之前声明为MyList<User*> Users;
(MyList 是一个列表 ADT,我有一个用户类)并且边声明为vector<string>edges
to what object
is this error referring?
什么object
是这个错误指?
回答by billz
GMLwriter::write
is not static function of GMLwriter, you need to call it through object. For example:
GMLwriter::write
不是 GMLwriter 的静态函数,你需要通过对象调用它。例如:
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:
如果GMLwriter::write
不依赖于任何 GMLwriter 状态(访问 的任何成员GMLwriter
),则可以将其设为静态成员函数。然后你可以不用对象直接调用它:
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);
回答by Pubby
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);
回答by Ronaldo Nazarea
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.
在这种情况下,您可能希望在声明之前使用 'static' 修饰符。