【问题标题】:How to declare a function returning a class instance, that is used in the same class?如何声明返回在同一个类中使用的类实例的函数?
【发布时间】:2021-08-25 07:28:30
【问题描述】:

我已经尝试了几周并搜索了几天的答案,但没有找到。我的代码相当大且相互交织,但我的问题在于 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_in_file() 函数。然后它像上面的代码一样工作(唯一的例外是朋友函数也是具有定义的实际函数)。但是我需要在没有声明 Word 对象的情况下使用该函数,因此它需要在类之外。我怎样才能让它发挥作用?

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

【问题讨论】:

  • 请发布minimal reproducible example 和编译器错误消息
  • 根据可用信息,search_in_file 似乎应该只是一个成员函数。在“this”对象中填写信息,并可能返回一个状态。
  • Word 代表什么,为什么它关心在文件中搜索字符串?
  • @nielsen 起初它是一个成员函数,但我需要它在其他非成员函数中声明 Words,虽然你的想法可行,但我认为,每次需要两行我想用它声明一个词:1)声明空词2)按照你的建议填写。但我希望它与一个一起工作:` Word any = search_in_file(); ` 无论如何,我得到了我正在寻找的遮阳篷。

标签: c++ friend-function non-member-functions


【解决方案1】:

你想要这个:

#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)
{
  //...
}

【讨论】:

  • 在将函数声明为友元之前不必声明它。我看不出这个答案有什么作用。 OP 需要提供更多信息。
  • @nielsen 是的,它是:godbolt.org/z/9Weexq6W3
  • 友元声明不是必须的,但在fill()的实现中使用前当然需要声明。最好将该实现从类声明中取出以避免Word 的前向声明,但这是个人喜好问题。无论如何,OP 仍然需要提供更多信息。
  • @nielsen - 你的想法可能也行得通,但我也有一个有同样问题的构造函数,我不想把它放在初始类定义之外,我也得到了它的工作方式我想要!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多