0

数週間試してみて、何日も答えを探しましたが、見つかりませんでした。私のコードはかなり大きく、絡み合っていますが、問題は 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 を使用しないため、機能すると思います。

4

1 に答える 1

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)
{
  //...
}
于 2021-06-08T09:22:16.250 に答える