Examples of why declaring data in a class as personal is important?

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?

+3
source share
7 answers

, " ". -, , - , ( , ). , , , .

:

class Stack
{
    public:
        int Items[10];
        int CurrentItemIndex;
}

CurrentItemIndex , . - , . - Items. - public, , .

private . , - , Items. , , , . , .

, , . x , , , .

+5

, , .

, , . , "", .

- , , , .

, . - , , .

, ?

, , , , .

, , , - , , , , .

, ? , . , , , .

+3

, , , . . , , , , . , .

+1

, 2 , , , 2 , 2 , .. , , , // . TORTOISE, , .

0

, "" ( ), , , , . , .

Eg. - , .

0

, - , ? ++.


, - , , . - , . - elses.

0

, 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. - , , .


, , ( ), . , , " " .

0

All Articles