如何在C ++中使用另一个类中两个变量的值

时间:2016-06-05 00:59:15

标签: c++

所以我希望能够在课程x中使用yextra的值,并将它们设置为zw

我似乎无法弄清楚它为什么不起作用。

我一直在尝试使用这个朋友班,但它没有用。

以下是代码:

#include <iostream>
using namespace std;

class extra;
class Regner
{
 friend class extra;

 public:

 void getInput();
 void calculate();

 private:

 double x;
 double y;
};

class extra
{
 public:

 extra ():z(0),w(0){}

 void bruger()
 {
    Regner one;
    z = one.x;
    w = one.y;
 }

 //void udfrabruger(){
    //cout<<"z/w = "<<z/w<<endl;
 //}

 private:

 double z, w;
};

int main()
{
 Regner find;          // construct a default object
 extra find2;
 find.getInput();      // ask for user input
 find.calculate();     // use it
 find2.bruger();
 //  find2.udfrabruger();
}

void Regner::getInput()
{
 cout << "Enter x: ";
 cin >> x;
 cout << "Enter y: ";
 cin >> y;
}

void Regner::calculate()
{
 cout << "x + y = " << x + y << endl;
 cout << "x - y = " << x - y << endl;
 cout << "x * y = " << x * y << endl;
}

1 个答案:

答案 0 :(得分:1)

findfind2不相关,直到您将其关联起来。

更改bruger函数以将Regner对象作为参数传递,而不是创建本地副本:

void bruger(Regner one)
{
    z = one.x;
    w = one.y;
}

然后,在main中将其称为:

find2.bruger(find);