函数使用对象和对象使用函数

时间:2016-04-26 12:56:59

标签: c++ c++11 cyclic-dependency

我基本上有一个循环依赖问题,其中函数使用对象对象,而对象使用所述函数。有没有办法解决这个问题而不解决它?

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

请注意,我理解这个例子很愚蠢,但这个例子只包含问题的本质和#34;它出现在更为复杂的情况下,我有时不知道如何解决它,或者即使它可以解决,并且能够做到这一点会非常方便。我问是否有办法做到这一点没有解决它。

1 个答案:

答案 0 :(得分: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); }
相关问题