5

我得到编译错误

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 是一个列表 ADT,我有一个用户类),边声明为vector<string>edges

object这个错误指的是什么?

4

3 回答 3

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);
于 2013-02-11T04:28:38.640 回答
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);
于 2013-02-11T04:30:01.720 回答
0

您可能正在尝试调用/创建一个静态方法,

在这种情况下,您可能希望在声明之前使用“静态”修饰符。

http://www.functionx.com/cppcli/classes/Lesson12b.htm

于 2013-02-11T04:34:10.440 回答