Accessing private members c++

人走茶凉 提交于 2019-12-22 09:16:03

问题


In this code why can I access the private member of the object with no compiler error?

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents=0)
    {
        m_nCents = nCents;
    }

    // Copy constructor
    Cents(const Cents &cSource)
    {
        m_nCents = cSource.m_nCents;
    }

    Cents& operator= (const Cents &cSource);

};

Cents& Cents::operator= (const Cents &cSource)
{

cSource.m_nCents is private why can I do the following:

    m_nCents = cSource.m_nCents;

    // return the existing object
    return *this;
}

回答1:


Because private means "visible accessible to the class", not "visible accessible to the object".




回答2:


You can access private members from member-functions/constructors/destructor/freinds of the class. It is class-based accessibility, not object-based accessibility.



来源:https://stackoverflow.com/questions/8547541/accessing-private-members-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!