访问私有成员 C++ [英] Accessing private members c++

查看:62
本文介绍了访问私有成员 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,为什么我可以在没有编译器错误的情况下访问对象的私有成员?

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 是私有的,为什么我可以执行以下操作:

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

    m_nCents = cSource.m_nCents;

    // return the existing object
    return *this;
}

推荐答案

因为 private 的意思是可见可供全班访问",而不是可见 对象可访问".

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

这篇关于访问私有成员 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆