Purpose of private members in a class

2020-02-03 04:29发布

What are the purposes of having private/protected members of a class/structure in object-oriented programming? What's the harm in having all members be public?

10条回答
ゆ 、 Hurt°
2楼-- · 2020-02-03 05:01

Sometime you don't want to reveal private information to everybody. E.g you don't want to let your age be known to public but you may want tell people if you are above 25.

查看更多
相关推荐>>
3楼-- · 2020-02-03 05:05

Metaphorically, exposing private members as public is like having an option on your car's dashboard that allows you to tweak the engine oil pressure.

The car should manage that internally (privately), and the user should be shielded from messing with it directly (encapsulation), for obvious reasons.

查看更多
做自己的国王
4楼-- · 2020-02-03 05:05

What are the purposes of having inner organs in the human body? What's the harm in having all organs outside?

Exactly!

The short answer would be: Because you need them so you can't live without them and you can't expose them to everyone to modify and play around with them because that could kill you (cause your class not to function properly).

查看更多
淡お忘
5楼-- · 2020-02-03 05:06

Nicely explained in Section 7.4: Protect your Private Parts of this online C++ tutorial.

Why bother with this stuff?

Specifiers allow a class to be very complex, with many member functions and data members, while having a simple public interface that other classes can use. A class which has two hundred data members and one hundred member functions can be very complicated to write; but if there are only three or four public member functions, and the rest are all private, it can be easy for someone to learn how to use the class. He only needs to understand how to use a small handful of public functions, and doesn't need to bother with the two hundred data members, because he's not allowed to access this data. He can only access the private data through the class' public interface. Without a doubt, in a small program, using these specifiers may seem unnecessary. However, they are worth understanding if you plan to do any program of reasonable size (more than a couple hundred lines). In general, it is good practice to make data members private. Member functions which must be called from outside the class should be public, and member functions which are only called from within the class (also known as "helper functions") should probably be private. These specifiers are especially useful in a large program involving more than one programmer.

The above explanation explains how using private eases the learning curve. Here's an example which explains the "code breaking" aspect:

Here's a class ParameterIO which reads and writes a vector of integer parameters

class ParameterIO
{
public:
    // Main member
    vector<int> *Params;
    string param_path;

    // Generate path
    void GeneratePath()
    {       
        char szPath[MAX_PATH];
        sprintf(szPath,"params_%d.dat",Params->size());
        param_path = szPath;
    }

    // Write to file
    void WriteParams()
    {
        assert_this(!Params->empty(),"Parameter vector is empty!");
        ofstream fout(param_path.c_str());
        assert_this(!fout.fail(),"Unable to open file for writing ...");
        copy(Params->begin(),Params->end(),ostream_iterator<int>(fout,"\n"));
        fout.close();
    }

    // Read parameters
    void ReadParams(const size_t Param_Size)
    {
        // Get the path
        Params->resize(Param_Size);
        GeneratePath();
        // Read
        ifstream fin(param_path.c_str());
        assert_this(!fin.fail(),"Unable to open file for reading ...");
        // Temporary integer
        for(size_t i = 0; i < Params->size() && !fin.eof() ; ++i) fin>>(*Params)[i];
        fin.close();
    }

    // Constructor
    ParameterIO(vector<int> * params):Params(params)
    {
        GeneratePath();
    }

    // Destructor
    ~ParameterIO()
    {
    }      

    // Assert
    void assert_this(const bool assertion, string msg)
    {
        if(assertion == false) 
        {
            cout<<msg<<endl;
            exit(1);
        }
    }
};

The following code breaks this class:

const size_t len = 20;
vector<int> dummy(len);
for(size_t i = 0; i < len; ++i) dummy[i] = static_cast<int>(i);
ParameterIO writer(&dummy);

// ParameterIO breaks here!
// param_path should be private because 
    // the design of ParameterIO requires a standardized path
writer.param_path = "my_cool_path.dat";
// Write parameters to custom path
writer.WriteParams();

vector<int> dunce;
ParameterIO reader(&dunce);
// There is no such file!
reader.ReadParams(len);
查看更多
登录 后发表回答