调用成员函数

本文详细解释了C++中const关键字的作用及其在类对象中的实现方式,包括如何通过构造函数进行初始化和避免意外修改const变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在课上,通过引用传递参数,我们覆盖的传递函数参数为const变量的优点。总的来说,决策变量常量确保它们的值是不小心更改。这是特别重要的传递变量的参考,为来电者一般不会期望值传递给一个函数被改变。

就像内置的数据类型(int,char,双,等),类的对象可以通过使用const关键字声明为const。所有的const变量必须在创建时初始化。在内置数据类型的情况下,在实例是通过显式或隐式的作业完成:

1
2
const int nValue = 5; // initialize explicitly
const int nValue2(7); // initialize implictly

在类的情况下,是通过构造函数初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Something
{
public:
    int m_nValue;
 
    Something() { m_nValue = 0; }
 
    void ResetValue() { m_nValue = 0; }
    void SetValue(int nValue) { m_nValue = nValue; }
 
    int GetValue() { return m_nValue; }
};
 
int main()
{
    const Something cSomething; // calls default constructor
 
    cSomething.m_nValue = 5; // violates const
    cSomething.ResetValue(); // violates const
    cSomething.SetValue(5); // violates const
 
    return 0;
}

所有三个涉及csomething以上线是非法的因为他们违反csomething试图改变一个成员变量或调用成员函数,试图改变一个成员变量的常量。

现在,考虑下面的电话:

1
std::cout << cSomething.GetValue();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值