简体   繁体   中英

NewBie: C++ Private Variables

So im learning c++ and my teacher was saying that you need intGetFoo() functions in order to return the private data . So for example i have this code

class Pseudorandon{

public:
   Pseudorandon( int Seed,int Multiplier,int Increment,int Modulus);
   void PerformAlga(int a, int b, int c, int d);
   void GetOutput();

private:
  int seed;
  int multiplier;
  int increment;
  int modulus;
  int Number;
  int Number2;
  int Number3;
  int Number4;
};

Main

Pseudorandon::Pseudorandon(int Seed,int Multiplier,int Increment,int Modulus){
  PerformAlga(Seed, Multiplier, Increment, Modulus);
}

void Pseudorandon::PerformAlga(int a, int b, int c, int d){
  seed=a;
  multiplier=b;
  increment=c;
  modulus=d;
}

void Pseudorandon::GetOutput(){
  Number =  (multiplier * seed + increment) % modulus;
  Number2 = Number;
  Number3 = (multiplier * Number2 + increment) % modulus;

  std::cout<<Number<<Number3;
}

int main(void)
{
  Pseudorandon ps(1,40,725,729);
  ps.GetOutput();
}

So what is the point of having intGetFoo() if I can get the data that is private using public function from my class without using a GET function.

When would I use getters ie ( intGetFoo(){return private variable} ). function or what are there purpose??

You only need getters and setters if you need to access data from outside the class. In your case it might be so you could say

  std::cout << "Output from seed=" << ps.GetSeed() << ", muliplier=" 
            << ps.GetMultiplier() << " = " << ps.GetOutput();

You don't need to use getters and setters from inside GetOutput

There is no point using GetFoo from inside GetOutput. Either you misunderstood what your teacher meant, or he doesn't know what he is talking about.

The point of public/private is to hide the implementation of your class from the users of your class. But when you are writing the methods of your class you are implementing it, not using it, so there is no problem using private members directly.

Private members are generally part of your internal state. Neither class users nor children class can access it. Typically seed in your case.

Sometimes, you may want to give access to the children classes and the class user a read-only access to part of your internal state: that's when you would use a getter!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM