如何访问与其他类不同的类中的变量? [英] How to access variables in different class from other class?

查看:69
本文介绍了如何访问与其他类不同的类中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有两个类, A B

这里是他们两个的代码

Let just say that we have two classes, A and B.
Here is code for both of them

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但我不想通过

我需要在函数<$ c $中找到x的一些方法,我可以看一下朋友和继承,但是似乎都没有帮助我,如果我错了,也可以纠正我。 c> FindY()。

我要使用静态方法,但在我的情况下我会遇到此错误。

the problem is that i want to access x but i don't wanna pass anything as argument to my function i look at friend and inheritance but both didn't seem to help me, correct me if i'm wrong.
some how i need to find x in function FindY().
I'm going with the static method but in my case i get this error.

错误2错误LNK2001:无法解析的外部符号 public:静态类 std :: vector< class GUIDialog *,class std :: allocator< class GUIDialog *>> Window :: SubMenu(?SubMenu @ Window @@ 2V?$ vector @ PAVGUIDialog @@ V?$ allocator @ PAVGUIDialog @@@ std @@@ std @@ A)C:\用户\ \所有者\文档\Visual Studio 2010\项目\Monopoly\Monopoly\Window.obj
这是我的声明方式

Error 2 error LNK2001: unresolved external symbol "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 Here is how i declared it

static vector<GUIDialog *> SubMenu;

由于此行,我得到了该错误

I get that error because of this line

SubMenu.resize(3);


推荐答案

三种不同的方法:


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

  1. Make B::FindY take an A object as a parameter

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


  • 设为A :: x静态

  • Make A::x static

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


  • 使B从A继承。

  • Make B inherit from A.

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


  • CashCow还指出了执行此操作的更多方法在他的回答中。

    CashCow also points out more ways to do this in his answer.

    这篇关于如何访问与其他类不同的类中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆