[英]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.