• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

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成员函数,不能调用其它成员函数。

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap