c++ - 函数使用对象,对象使用函数

标签 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); }
};

请注意,我知道这个例子很愚蠢,但这个例子只包含“问题的本质”,它出现在更复杂的情况下,有时我不知道如何解决它,或者即使它可以可以变通,只要能做到就很方便了。我想问是否有办法解决这个问题。

最佳答案

声明结构定义中的构造函数,然后将定义移出结构并将其与函数一起放置在结构定义下方:

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/

相关文章:

c++ - 防止 C++03 代码在 C++11 中表现不佳的好方法?

c++ - 我应该在 dlopen 之前锁定吗?

C++ 模板类从静态助手调用自己的构造函数

c++ - std::unique_ptr 继承切片和析构函数

C++ 错误 : "' class' does not name a type"and "invalid use of incomplete type ‘struct ...' "

c++ - 如何在后续流程启动时确保 RNG 的唯一种子?

c++ - 如何定义嵌套类并使用它

c++ - 防止 const 类函数在引用成员上调用非 const 类函数

node.js - 如何处理 Node.js 中的循环依赖

react-native - 如何检测 native react 中的循环依赖项导入?