search

Home  >  Q&A  >  body text

c++ - 被包含类的函数怎么访问包含类的成员或函数

class A
{
    A();
    void func();
};

class B
{
    A a;
    int getX() {return x;}
private:
    int x;
};

请问怎么做才能让A的func()访问到x?
因为我想让a变量的func()访问x成员。

巴扎黑巴扎黑2804 days ago611

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:23:20

    Originally I wanted to access B’s x in A’s func(), but later I found out that I could add a function to B to access A’s.
    Including can access the included, and the included cannot access the included. This should generally be the case.

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:23:20

    I am also a beginner in C++. Is there any other use for declaring A as a member of B? If B is not directly declared as a friend function of A, the members of B can be accessed through A, including private members.

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:23:20

    How can I make func() of A access x? Because I want func() of variable a to access the x member.

    Please see Section 7.2.1 and Section 7.3.4 of "C++ Primer" for an explanation of Friendship.

    class B
    {
        friend void A::func();
        // . . .
    };

    reply
    0
  • Cancelreply