C++ 函数使用对象,对象使用函数
我基本上有一个循环依赖性问题,函数使用对象对象,对象使用所述函数。有没有办法解决这个问题而不去解决它C++ 函数使用对象,对象使用函数,c++,c++11,cyclic-dependency,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 weigh
//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); }
仅在结构定义中声明构造函数,然后将定义移出结构,并将其与函数一起放置在结构定义下面:
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); }
您只需要在通常的.h和.cpp文件之间分割声明和实现该函数更适合作为成员函数。@JoachimPileborg在回答中说:“注意,我理解这个例子很愚蠢,但这个例子只包含“问题的本质”,在更复杂的情况下,我有时不知道如何解决它,甚至不知道是否可以解决它。”您只需要在通常的.h和.cpp文件之间分割声明和实现该函数更适合作为成员函数。@JoachimPileborg在回答中说:“注意,我理解这个例子很愚蠢,但这个例子只包含“问题的本质”,在更复杂的情况下,我有时不知道如何解决它,甚至不知道是否可以解决它。”问题得到了回答,但请注意代码没有编译:对
change\u weight
的调用缺少一个参数。此外,potato
是按值传递的。@Quentin我编辑后在末尾添加了一个分号,并在我的问题和这个答案中将按值传递改为按引用传递(我在Ideone上测试了它)。问题得到了回答,但请注意代码没有编译:调用change\u weight
缺少一个参数。此外,potato
是按值传递的。@Quentin我编辑后在末尾添加了一个分号,并在我的问题和这个答案中将按值传递改为按引用传递(我在Ideone上测试了它)