0

私は基本的に、関数がオブジェクトオブジェクトを使用し、オブジェクトがその関数を使用するという循環依存の問題を抱えています。これを回避せずに解決する方法はありますか?

//function that uses struct
void change_weight(Potato* potato,float byX) { potato->weight+=byX; }
//said struct that uses said function
struct Potato
{
    float weight=0.0;
    Potato(float weightin) { change_weight(weightin); }
};

この例がばかげていることは理解していますが、この例には「問題の本質」しか含まれていないことに注意してください。 、そしてそれができるだけでとても便利です。回避せずにこれを行う方法があるかどうかを尋ねています。

4

1 に答える 1

3

構造体定義でコンストラクターのみを宣言してから、定義を構造体の外に移動し、関数と一緒に構造体定義の下に配置します。

struct Potato
{
    float weight=0.0;
    Potato(float weightin);  // Only declare constructor
}

//function that uses struct
void change_weight(Potato potato,float byX) { potato.weight+=byX; }

// Define the constructor
Potato::Potato(float weightin) { change_weight(*this, weightin); }
于 2016-04-26T13:01:03.587 に答える