Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c++ - How to access variables in different class from other class?

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();
}

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.

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:UsersOwnerdocumentsvisual studio 2010ProjectsMonopolyMonopolyWindow.obj Here is how i declared it

static vector<GUIDialog *> SubMenu;

I get that error because of this line

SubMenu.resize(3);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Three different approaches:

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

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

    class A {
    public:
      static int x;
    };
    class B {
    public:
      void FindY() { y = A::x + 12; }
    };
    
  3. Make B inherit from A.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...