如何在同一个类中将两个值从一个函数传递给另一个函数?

Sam*_*uel 1 c++

我有这个功能:

void fraction::init()
{
  cout<<"enter the values for the numerator and denominator\n";
  cin>>num;
  cin>>denom;
}
Run Code Online (Sandbox Code Playgroud)

我希望这两个数字用于操纵它们的另一个函数.我该如何将它们带到其他功能?注意:两个功能属于同一类.

And*_*ter 5

只需将它们定义为类的成员:

class fraction {
private:
  int num;
  int denom;

public:
   void init();          // has access to num and denom
   void otherMethod();   // also has access to num and denom
};
Run Code Online (Sandbox Code Playgroud)

您也不应该依赖于使用默认值init()调用初始化变量,并且您也不应该依赖C++提供的各种默认初始化,请参阅默认变量值.

相反,添加一个构造函数,该构造函数为变量设置默认值,以确保在创建类的对象后变量具有合理的值.然后,你仍然可以调用init()设置你想要的任何值(并且你可能应该重命名init()为类似于readValues()反映方法真正做的事情).