Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...