C ++ class friend

I am trying to compile a code like this:

#include <iostream>
using namespace std;

class CPosition
{
  private:
    int itsX,itsY;
  public:
    void Show();
    void Set(int,int);
};

void CPosition::Set(int a, int b)
{
  itsX=a;
  itsY=b;
}

void CPosition::Show()
{
    cout << "x:" << itsX << " y:" << itsY << endl;
}

class CCube
{
  friend class CPosition;
  private:
         CPosition Position;
};

main()
{
  CCube cube1;

  cube1.Position.Show();
  cube1.Position.Set(2,3);
  cube1.Position.Show();
}

but get 'CCube :: Position' is not available in the main () function 3 times. I want the CPosition class to be declared outside of CCube so that I can use it in future in new classes, for example. CBall :) but how can I make it work without using inheritance. Is it possible:)?

Regards, PC

+3
source share
7 answers

In addition to regular getters, you must also have a const getter.
Pay attention to the return link. This allows you to make any call to SetXX () affect the copy of the position inside CCube, and not the copy that you updated.

class CCube
{
    private:
        CPosition Position;
    public:
        CPosition&       getPosition()       { return Position; }
        CPosition const& getPosition() const { return Position; }
};
+5
source

friend class CPosition; , CPosition CCube. , . , :

class CCube
{
     public:
         CPosition Position;
};
+4

errr, no, Position "main"

... getter

+1

friend int main();

"" CCube.

+1

, . : , CPosition (itsX, itsY)? , . , CPosition X Y, .

, , . .

0

, :

class CCube
{
  private:
         CPosition Position;
  public:
  CPosition& getPosition() { return Position; }
};

main()
{
  CCube cube1;

  cube1.getPosition().Show();
  cube1.getPosition().Set(2,3);
  cube1.getPosition().Show();
}

0

3 :

  • CPosition
  • ( CPosition, int radius - )
  • friend

, CPosition . , . 1 .

, CCube CCube, :

  • CCube::Position
  • - CCube::MoveTo( const CPosition& p ) CCube::GetPosition() const.

As @Firas said: don't play with frienduntil you make sure you need it.

0
source

Source: https://habr.com/ru/post/1698856/


All Articles