c语言 关键字const_C ++ const关键字| 查找输出程序| 套装2

c语言 关键字const

Program 1:

程序1:

#include <iostream>
using namespace std;

class Sample {
    int A;
    int B;

public:
    Sample(): A(10), B(20)
    {
    }

    void set(int a, int b) const
    {
        A = a;
        B = b;
    }
    void print()
    {
        cout << A << " " << B;
    }
};

int main()
{
    Sample S;

    S.print();

    return 0;
}

Output:

输出:

main.cpp: In member function 'void Sample::set(int, int) const':
main.cpp:15:13: error: assignment of member 'Sample::A' in read-only object
         A = a;
             ^
main.cpp:16:13: error: assignment of member 'Sample::B' in read-only object
         B = b;
             ^

Explanation:

说明:

The above code will generate an error because in the above program we defined a const member function. And we are trying to modify the value of data members in const member function set().

上面的代码将产生错误,因为在上面的程序中我们定义了const成员函数。 而且我们正在尝试在const成员函数set()中修改数据成员的值。

In C++, we cannot modify values in a const member function.

在C ++中,我们无法在const成员函数中修改值。

Program 2:

程式2:

#include <iostream>
using namespace std;

int main()
{
    int X = 10;
    int* const ptr = &X;

    *ptr = 20;

    cout << X;

    return 0;
}

Output:

输出:

20

Explanation:

说明:

Here we declared a variable X with initial value 10. We need to understand the below statement carefully.

在这里,我们声明了一个初始值为10的变量X。我们需要仔细理解以下语句。

in the above statement, ptr is constant, we cannot move the pointer in the backward or forward direction for address displacement, but *ptr it means we can modify the value because * is a value of the operation. And ptr contains the address of X, then we can modify the value of X.

在上面的语句中, ptr是常量,我们不能向后或向前移动指针以进行地址移位,但是* ptr表示我们可以修改该值,因为*是该操作的值。 ptr包含X的地址,那么我们可以修改X的值。

Then the final value is 20.

那么最终值为20。

Recommended posts

推荐的帖子

翻译自: https://www.includehelp.com/cpp-tutorial/const-keyword-find-output-programs-set-2.aspx

c语言 关键字const

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值