【问题标题】:Function uses object and object uses function函数使用对象,对象使用函数
【发布时间】:2016-08-20 07:45:31
【问题描述】:

我基本上有一个循环依赖问题,其中一个函数使用一个对象对象,而该对象使用该函数。有什么方法可以在不解决此问题的情况下解决此问题?

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

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

【问题讨论】:

  • 您只需要在通常的 .h 和 .cpp 文件之间拆分声明和实现。
  • 虽然代码只是一个示例,但它是一个非常糟糕的代码...... :) 该函数更适合作为成员函数。
  • @JoachimPileborg 在回答中:“请注意,我理解这个例子很愚蠢,但这个例子只包含“问题的本质”,它出现在更复杂的情况下,有时我不会知道我将如何解决它,或者即使它可以解决”

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


【解决方案1】:

声明结构体定义中的构造函数,然后将定义移出结构体,与函数一起放在结构体定义下面: p>

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

【讨论】:

  • 问题已得到解答,但请注意代码无法编译:对change_weight 的调用缺少参数。而且potato是按值传递的。
  • @Quentin 我编辑在末尾添加了一个分号,并在我的问题和这个答案中将按值传递更改为按引用传递(我在 Ideone here 上对其进行了测试)跨度>
猜你喜欢
  • 2012-04-27
  • 1970-01-01
  • 2020-11-20
  • 2018-08-04
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
相关资源
最近更新 更多