成员函数常量

重载函数与一个const和非const版本通常是当返回值需要不同的常量。在上面的例子中,对getvalue() const版本返回const引用,而非const版本返回一个非const引用。

让我们使我们的日期类的成员函数常量可以使用const对象看日期:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Date
{
private:
    int m_nMonth;
    int m_nDay;
    int m_nYear;
 
    Date() { } // private default constructor
 
public:
    Date(int nMonth, int nDay, int nYear)
    {
        SetDate(nMonth, nDay, nYear);
    }
 
    void SetDate(int nMonth, int nDay, int nYear)
    {
        m_nMonth = nMonth;
        m_nDay = nDay;
        m_nYear = nYear;
    }
 
    int GetMonth() { return m_nMonth; }
    int GetDay()  { return m_nDay; }
    int GetYear() { return m_nYear; }
};

唯一的非构造函数的成员函数不能修改成员变量(或调用函数修改成员变量)是访问功能。因此,他们应该是。这里是我们的日期类const版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Date
{
private:
    int m_nMonth;
    int m_nDay;
    int m_nYear;
 
    Date() { } // private default constructor
 
public:
    Date(int nMonth, int nDay, int nYear)
    {
        SetDate(nMonth, nDay, nYear);
    }
 
    void SetDate(int nMonth, int nDay, int nYear)
    {
        m_nMonth = nMonth;
        m_nDay = nDay;
        m_nYear = nYear;
    }
 
    int GetMonth() const { return m_nMonth; }
    int GetDay() const { return m_nDay; }
    int GetYear() const { return m_nYear; }
};


常量成员函数是C++中的一种特殊类型成员函数,它被声明为 `const`,表示该函数不会修改对象的状态。换句话说,常量成员函数只能读取对象的数据成员,而不能修改它们。 ### 1. **常量成员函数的定义**: 常量成员函数通过在函数声明和定义的参数列表之后添加 `const` 关键字来实现。这表明该函数不会修改类的任何非静态数据成员。 ```cpp class MyClass { private: int value; public: MyClass(int v) : value(v) {} // 常量成员函数 int getValue() const { return value; // 只读取数据成员 } // 非常量成员函数 void setValue(int v) { value = v; // 修改数据成员 } }; ``` ### 2. **为什么需要常量成员函数?** - **保护对象状态**:当一个对象被声明为 `const` 时,只能调用它的常量成员函数。这样可以确保对象的状态不会被意外修改。 - **提高代码安全性**:通过将某些函数声明为 `const`,可以明确地告诉调用者这些函数不会改变对象的状态,从而提高代码的安全性和可读性。 ### 3. **常量成员函数的特点**: - **不能修改非静态数据成员**:常量成员函数不能修改类的任何非静态数据成员。 - **不能调用非常量成员函数**:常量成员函数不能调用同一个类中的非常量成员函数。 - **可以调用其他常量成员函数**:常量成员函数可以调用同一个类中的其他常量成员函数。 - **可以访问静态数据成员**:常量成员函数可以访问类的静态数据成员,因为静态数据成员不属于特定的对象实例。 ### 4. **代码示例**: ```cpp #include <iostream> using namespace std; class MyClass { private: int value; public: MyClass(int v) : value(v) {} // 常量成员函数 int getValue() const { return value; // 只读取数据成员 } // 非常量成员函数 void setValue(int v) { value = v; // 修改数据成员 } }; int main() { const MyClass obj(10); // 常量对象 // 调用常量成员函数 cout << "Value: " << obj.getValue() << endl; // 输出 10 // 下面这行代码会导致编译错误,因为 setValue 是非常量成员函数 // obj.setValue(20); return 0; } ``` ### 解释 常量成员函数的主要目的是确保对象的状态不会被修改。当你希望某个函数只读取对象的数据而不修改它时,使用 `const` 是一种很好的实践。此外,`const` 成员函数可以被常量对象调用,而普通成员函数则不能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值