我基本上有一个循环依赖问题,其中一个函数使用一个对象对象,而该对象使用所述函数。有什么办法可以解决这个问题而不解决它吗?
//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); }
};
请注意,我知道这个例子很愚蠢,但这个例子只包含“问题的本质”,它出现在更复杂的情况下,有时我不知道如何解决它,或者即使它可以可以变通,只要能做到就很方便了。我想问是否有办法解决这个问题。
最佳答案
仅声明结构定义中的构造函数,然后将定义移出结构并将其与函数一起放置在结构定义下方:
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); }
关于c++ - 函数使用对象,对象使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36865632/