I understand that only a class can access the data, therefore it is “safer” and what is not, but I really don’t understand why this is such a big deal. Perhaps this is due to the fact that I did not make the programs complex enough so that the data could accidentally change, but it is a little confusing when teaching classes and says that making things private is important because it is “safer” when the only time when I changed the data in the program - this is when I clearly wanted to. Can someone give some examples where the data would be inadvertently changed if the data were not private?
, " ". -, , - , ( , ). , , , .
:
class Stack { public: int Items[10]; int CurrentItemIndex; }
CurrentItemIndex , . - , . - Items. - public, , .
CurrentItemIndex
Items
public
private . , - , Items. , , , . , .
, , . x , , , .
, , .
, , . , "", .
- , , , .
, . - , , .
, ?
, , , , .
, , , - , , , , .
, ? , . , , , .
, , , . . , , , , . , .
, 2 , , , 2 , 2 , .. , , , // . TORTOISE, , .
, "" ( ), , , , . , .
Eg. - , .
, - , ? ++.
, - , , . - , . - elses.
, BankAccount, NIP . , :
class BankAccount { public: std::string NIP; int cash; };
, . , ( ). , , , , .
, , , , . , :
class BankAccount { public: int getCash() const { return cash; } void setCash(int amount) { if (amount >= 0) cash = amount; else throw std::runtime_exception("Cash amount is negative."); } private: int cash; }
? . Find and Replace : accessors getCash() seters setCash. - , , .
, , ( ), . , , " " .