2013-02-11 67 views
5

我得到的编译错误不能调用成员函数没有对象错误 - 在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是一个List ADT和我有一个User类)和边缘都被定义为vector<string>edges

什么object这个错误是指?

+0

你是怎么称呼这个功能的?你需要显示那部分代码才能得到正确答案而不是猜测。 – 2013-02-11 04:28:39

+0

@AlokSave'GMLwriter :: write(argv [3],Users,edges);' – user2059901 2013-02-11 04:29:38

+0

那么这就是**不是定义**,在C++中要能够调用非静态成员函数,您需要一个类目的。例如:'GMLwriter obj; obj.write(...);' – 2013-02-11 04:30:48

回答

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

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);