如何声明返回类实例的函数,该函数在同一个类中使用



我试了几个星期,找了好几天都没有找到答案。我的代码很大,而且相互交织,但我的问题是3个函数/类,因此我只显示我的声明和相关信息。我有以下不可编译的代码:

class Word{
private:
*members*
public:
//friend declaration so i could access members and use it in class - doesn't help
friend Word search_in_file(const string& searchee);
//function that uses previous function to create a Word object using data from file:
//type int to show it succeeded or failed
int fill(const string& searchee){
Word transmission = search_in_file(searchee);
//here are member transactions for this->members=transmission.member;
}
};
//function to return Word class from file:
Word search_in_file(const string& searchee){
//code for doing that
}

我已经尝试了所有可以声明函数或类的可能性,但没有找到解决方案。起初,我只在构造函数中使用了search_in_file((函数(现在它与函数fill((有相同的问题(,并在类中声明和定义了search_infile((函数。然后它按照上面的代码工作(唯一的例外是友元函数也是有定义的实际函数(。但我需要在没有声明Word对象的情况下使用该函数,因此它需要在类之外。我怎样才能让它工作?

我还应该指出,我有另一个使用Word作为参数的非成员函数,该函数适用于上述解决方案。尽管它有一个重载版本,但它并没有使用Word作为类之前声明的参数,我认为这就是它工作的原因。

您想要的是:

#include <string>
using namespace std;
// declare that the class exists
class Word;
// Declare the function   
Word search_in_file(const string& searchee);
class Word {
private:

public:
//friend declaration so i could access members and use it in class - doesn't help
friend Word search_in_file(const string& searchee);
//function that uses previous function to create a Word object using data from file:
//type int to show it succeeded or failed
int fill(const string& searchee) {
Word transmission = search_in_file(searchee);
//here are member transactions for this->members=transmission.member;
}
};
// Now class Word is completely defined and you can implement the function
Word search_in_file(const string& searchee)
{
//...
}

相关内容

最新更新