开发者

How to call-by-reference a variable of one class from another in C++

I have a class, let's call it class A, that is performing a calculation which returns a value of int value, and another class in my system, class B needs to use int value for further calculations. My plan is to use a third class, class C, where the variable will be defined, to pass the variable between A and B, with these two just working from references to the int value in class C. My problem is I don't know how to reference a variable in another class without first instantiat开发者_StackOverflow中文版ing some class or another, with the ensuing construction potentially overwriting int value.


Update: The code below outlines what I'm trying to achieve. I'm am trying to have variable

class A
{
public:
    void calculation1()
};

void A::calculation1()
{
    value = 10;
}

class B
{
public:
    void calculation2();
};

void B::calculation2()
{
    for (int count = 0; count < value; count ++)
    {
        // Do stuff here
    }
}

class C
{
    int value;
}


I believe you're not going in the right direction here. If I rephrase your problem description in pseudo-code, I get something like :

// The second calculation result depends on the result of the first one, so we
// provide it as a parameter.
int firstValue = calculationA();
int secondValue = calculationB(firstValue);

This is perfectly valid in itself : you just have to implement two free functions calculationA and calculationB and there is no need for classes of anything like it. Now, if you really want to put classes around this, you can.

What you need to understand is that classes interaction are a consequence of their respective responsibilities, not the opposite. For example, if the result of calculation1 has absolutely no utility beside being fed to calculation2, maybe the two functions shouldn't belong to different classes. Identify the responsibilities, try to express them as classes, and the interaction will appear naturally.


Why not just have a set function in class B, where you can set the value to what the calculation in A returns?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜