面向对象程序设计-C++_课时19const_课时20不可修改的

 

error C2131: 表达式的计算结果不是常数

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void main()
 5 {
 6     const int class_size = 12;
 7     int finalGrade[class_size];
 8 
 9     int a = 12;
10     int arr[a];//error C2131: 表达式的计算结果不是常数
11 
12     int x;
13     std::cin >> x;
14     const int size = x;
15     double classAverage[size];//error C2131: 表达式的计算结果不是常数
16 
17     system("pause");
18 }

 

指向常量的指针

const int * p;

常量指针

int x=5;

int * const p=&x;

指向常量的常量指针

int x=2;

const int * const p=&x;

 

error C3892: “s1”: 不能给常量赋值

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void main()
 5 {
 6     const char * s1 = "hello world";
 7     char s2[] = "hello world";
 8 
 9     std::cout << s1 << std::endl;
10     std::cout << s2 << std::endl;
11 
12     s1[0] = 'a';//error C3892: “s1”: 不能给常量赋值
13     s2[0] = 'a';
14 
15     std::cout << s1 << std::endl;
16     std::cout << s2 << std::endl;
17 
18     printf("s1=%p\n", &s1);
19     printf("s2=%p\n", &s2);
20 
21     system("pause");
22 }

 

const对象

1常量成员

2常引用作为函数参数

3常对象

类名 const 对象名(参数表);//必须初始化

4常成员函数

类型标识符 函数名(参数列表) const;

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A
 5 {
 6     const int i;
 7 public:
 8     A() :i(0)
 9     {
10 
11     }
12     void f()
13     {
14         std::cout << "f()" << std::endl;
15     }
16     void f() const
17     {
18         std::cout << "f() const" << std::endl;
19     }
20 };
21 
22 void main()
23 {
24     const A a;
25     a.f();
26 
27     A a1;
28     a1.f();
29 
30     system("pause");
31 }

 

在常成员函数里,不能更新对象的数据成员,也不能调用该类中没有用const修饰的成员函数。如果将一个对象说明为常对象,则通过该对象只能调用它的const成员函数,不能调用其它成员函数。

 

转载于:https://www.cnblogs.com/denggelin/p/5635356.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值