c++成员函数const_C ++中的const成员函数

c++成员函数const

C ++常量成员函数 (C++ Const Member Functions)

A constant (const) member function can be declared by using const keyword, it is used when we want a function that should not be used to change the value of the data members i.e. any type of modification is not allowed with the constant member function.

常量(const)成员函数可以使用const关键字声明,当我们想要一个不应用于更改数据成员值的函数时,即使用常量 成员函数时,不能使用任何类型的修改。

Example:

例:

Here, we have a class named "Numbers" with two private data members a and b and 4 member functions two are used as setter functions to set the value of a and b and 2 are constant members functions which are using as getter functions to get the value of a and b.

在这里,我们有一个名为“ Numbers”的类,具有两个私有数据成员a和b和4个成员函数,两个用作设置函数来设置a和b的值,而2是常量成员函数,用作getter函数来获取a和b的值。

Program:

程序:

#include <iostream>
using namespace std;

class Numbers
{
    private:
        int a;
        int b;
    public:
        Numbers() {a = 0; b = 0;}
        
        //setter functions to set a and b
        void set_a(int num1)
        {
            a = num1;
        }
        void set_b(int num2)
        {
            b = num2;
        }
        
        //getter functions to get value of a and b
        int get_a(void) const
        {
            return a;
        }
        int get_b(void) const
        {
            return b;
        }
};

//Main function
int main()
{
    //declaring object to the class
    Numbers Num;
    //set values
    Num.set_a(100);
    Num.set_b(100);
    
    //printing values
    cout<<"Value of a: "<<Num.get_a()<<endl;
    cout<<"Value of b: "<<Num.get_b()<<endl;
    
    return 0;
}

Output

输出量

Value of a: 100
Value of b: 200


翻译自: https://www.includehelp.com/cpp-programs/const-member-functions.aspx

c++成员函数const

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值