LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 240|回复: 0

C++混合访问修饰符

[复制链接]
发表于 2024-1-10 22:27:25 | 显示全部楼层 |阅读模式
类通常使用多种访问修饰符来设置其内部成员的访问级别。在类中使用访问修饰符并没有数量上的限制。

通常情况下,成员变量一般设置为私有,成员函数则设置为公有。我们会在下一节告诉你为什么。

规则:除非你有什么特殊的理由,不然就让成员变量私有,让成员方法公有。

观察下面的例子,它是一个同时使用了private和public访问修饰符的类。

#include <iostream>

class DateClass // members are private by default
{
    int m_month; // private by default, can only be accessed by other members
    int m_day; // private by default, can only be accessed by other members
    int m_year; // private by default, can only be accessed by other members

public:
    void setDate(int month, int day, int year) // public, can be accessed by anyone
    {
        // setDate() can access the private members of the class because it is a member of the class itself
        m_month = month;
        m_day = day;
        m_year = year;
    }

    void print() // public, can be accessed by anyone
    {
        std::cout << m_month << "/" << m_day << "/" << m_year;
    }
};

int main()
{
    DateClass date;
    date.setDate(10, 14, 2020); // okay, because setDate() is public
    date.print(); // okay, because print() is public

    return 0;
}
这段程序输出:

10/14/2020

尽管我们不能在main函数里访问m_month、m_day、m_year(因为它们是私有的),但我们可以通过它的公有成员函数setDate()和print()对这些私有变量进行间接访问。

一个类的公有成员通常又被成为公共接口(public interface)。因为只有公公成员可以在类的外部被访问,公共接口定义了使用这个类的程序如何与这个类进行交互。注意上面的main函数,被严格限制只能设置日期和输出日期,DateClass保护它的成员变量不会被直接访问和编辑。

有些程序员喜欢把私有成员写在前面,因为公有成员一般都会使用私有成员,所以理所当然地把私有成员写在前面。然而,类的使用者并不关心私有成员,所以公有成员应该写在前面。无论哪种方式,都是可取的。

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表