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

Ram*_*lol 2 c++ visual-c++

我们假设我们有两个类,A并且B.
这是他们两个的代码

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();
}
Run Code Online (Sandbox Code Playgroud)

问题是,我想访问x,但我不想传递任何东西作为我的功能的参数我看看朋友和继承,但两者似乎没有帮助我,纠正我,如果我错了.
一些我如何在功能中找到x FindY().
我要使用静态方法,但在我的情况下,我得到这个错误.

错误2错误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;
Run Code Online (Sandbox Code Playgroud)

由于这条线,我得到了那个错误

SubMenu.resize(3);
Run Code Online (Sandbox Code Playgroud)

vil*_*pam 8

三种不同的方法:

  1. 使B :: FindY将A对象作为参数

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

    class A {
    public:
      static int x;
    };
    class B {
    public:
      void FindY() { y = A::x + 12; }
    };
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使B继承自A.

    class B : public A {
    public:
      void FindY() { y = x + 12; }
    };
    
    Run Code Online (Sandbox Code Playgroud)

CashCow还在他的回答中指出了更多的方法.

  • 虽然答案在技术上是正确的,但应建议原始海报(OP)了解真正的类和对象. (3认同)