在另一个类函数中更改成员变量值?

时间:2014-11-30 03:59:13

标签: c++ class console

我一直在尝试制作一个基于短信的RPG游戏,并且如果你得到某个项目它会做某些事情。无论如何,我想要做的是从另一个类函数更改一个类变量。我该怎么做呢?我为你们编写了一些示例代码,看看我想要做什么。没有错误它只是不起作用。谢谢。

#include<iostream>
using namespace std;


// First class where we add values

class B
{
public:
    void AddValueB(int VALUE);
    int GetValueB(void);
    B();


private:
int value;;

};
// constructor
B::B(void)
{
    value=100;
}
// where we add the passed in value to our main value variable. 
void B::AddValueB(int VALUE)
{
    value+=VALUE;

}
// returns the final value
int B::GetValueB(void)
{
    return value;

}

//**Second Class**

class A
{
public:
    void SetValueA(int VALUE);
    int GetValueA(void);
    A();


private:
    int value;;

};
// constructor
A::A(void)
{

}
// sets value
void A::SetValueA(int VALUE)
{
    B b;
    value=VALUE;
// if value is one we pass 25 in B's AddValue() function which then should add 25 to the  value      variable. 
    if(value==1)
    {
        cout << "Should Be 125?\n\n";
        b.AddValueB(25);
    }
}
// returns value 
int A::GetValueA(void)
{
    return value;

}
//main
int main()
{
    A a;
    B b;
    // set A's value to 1 to trigger the if statement in the function which should add 25 to B's   value variable. 
    a.SetValueA(1);
    //output the final value for B.....still 100...why?
    cout << b.GetValueB();

    cin.get();

    return 0;


}

2 个答案:

答案 0 :(得分:1)

void A::SetValueA(int VALUE)中,您要在堆栈上创建B并设置其值。它对B中创建的main没有影响。如果您想在B中设置main的值A::setValueA,则必须将其传递给函数。

首先,更改类接口

class A
{
public:
    void SetValueA(int VALUE, B& b);
    int GetValueA(void);
    A();


private:
    int value;;

};

然后,改变实施。

void A::SetValueA(int VALUE, B& b)
{
    value=VALUE;
    if(value==1)
    {
        cout << "Should Be 125?\n\n";
        b.AddValueB(25);
    }
}

然后,将呼叫更改为A::SetValueA中的main

int main()
{
    A a;
    B b;
    a.SetValueA(1, b);
    cout << b.GetValueB();

    cin.get();

    return 0;
}

答案 1 :(得分:1)

friend functions可能很有用,但是如果你要改变其他类的值,那么它可能是不好的风格。

class A
{
    private:
        // private stuff
    public:
        //public stuff
        friend class B
}

class B
{
    private:
        // private stuff
    public:
        //public stuff
        friend class A
}

然后两个班级都可以直接访问彼此的成员。

相关问题