gpt4 book ai didi

c++ - 如何从其他类访问不同类中的变量?

转载 作者:太空狗 更新时间:2023-10-29 23:42:23 24 4
gpt4 key购买 nike

假设我们有两个类,AB .
这是他们两个的代码

class A
{
public:
int x;
};

class B
{
public:
int y;
void FindY() { y = x + 12; }
};

void something()
{
A fs;
B fd;
fs.x = 10;
fd.FindY();
}

问题是我想访问 x 但我不想将任何东西作为参数传递给我的函数我查看了友元和继承,但两者似乎都没有帮助我,如果我错了请纠正我。< br/>我需要如何在函数 FindY() 中找到 x .
我正在使用静态方法,但在我的例子中我得到了这个错误。

错误 2 error LNK2001: 未解析的外部符号 "public: static class std::vector<class GUIDialog *,class std::allocator<class GUIDialog *> > Window::SubMenu" (?SubMenu@Window@@2V?$vector@PAVGUIDialog@@V?$allocator@PAVGUIDialog@@@std@@@std@@A) C:\Users\Owner\documents\visual studio 2010\Projects\Monopoly\Monopoly\Window.obj这是我声明它的方式

static vector<GUIDialog *> SubMenu;

因为这一行我得到了那个错误

SubMenu.resize(3);

最佳答案

三种不同的方法:

  1. 让B::FindY接受一个A对象作为参数

    class B {
    public:
    void FindY(const A &a) { y = a.x + 12; }
    };
  2. 使 A::x 静态化

    class A {
    public:
    static int x;
    };
    class B {
    public:
    void FindY() { y = A::x + 12; }
    };
  3. 让 B 继承 A。

    class B : public A {
    public:
    void FindY() { y = x + 12; }
    };

CashCow 在他的回答中还指出了更多的方法来做到这一点。

关于c++ - 如何从其他类访问不同类中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4507822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com