jeudi 2 novembre 2017

Giving external functions access to private members of a class - C++

I am working on a simple cpp code which is as follows -

using namespace std;

class MyClass
{
public:
  MyClass(int num, int time, string some_text, MyCode value)
    :n_(num)
    ,t_(time)
    ,text_(some_text)
    ,val_(MyCode)
  {
    // Constructor body
  }
  ~MyClass();

private:
  num n_;
  time t_;
  some_text text_;
  MyCode val_;
 };
int MyClass::MyFunc()
{
  return 0;
}

void MyClass::MyFuncSet()
{
  return;
}

int main()
{
  MyClass m;
  m.MyFunc();
  m.MyFuncSet();
}

Now I want my functions MyFunc and MyFuncSet to be able to access the private members of my class. I was thinking of adding friend functions in my class like the following -

friend int MyFunc();
friend void MyFuncSet();

Is this the correct approach? Or should I add a setter function?

Aucun commentaire:

Enregistrer un commentaire