我是靠谱客的博主 感性白云,这篇文章主要介绍const成员和对象,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Foo { void show()const{ cout<<"Sad"<end;}//const常方法 } 这样加了const的成员函数后,就会提示编译器,该成员函数不会对成员变量进行修改,而且也无法修改 这个const修饰的是this指针,通过修改this指针的属性,进而修改函数功能 ************************************************************************************************* 如果想在加了const修饰的成员函数中修改变量的值,可以在定义变量是加上mutable,这样就破坏了这种机制 mutable int num; 对于const修饰的方式方法普通对象和常对象都可以调用 常方法内不能调用普通方法,是因为参数表的类型不能转换 但是普通方法可以调用常方法 如果定义了一个const Student s1; 然后通过s1.show();去调用一个普通类型方法,这样是错误的原因是: 不能将this指针从const Student*this转换为Student*this然后调用show函数 所以在日后我们写这些不修改成员变量的函数时,要加上const,达到保护对象的作用。 同时如果在成员函数上加上了const,那么其返回值的this指针类型为 const Foo * const thisconst Foo f1; 这时定义了一个const对象,被const修饰的对象称为常量对象,它只能调用被const修饰的成员函数 class Foo { void hello(){ cout<<"hello<<endl;} void hello()const { cout<<"word"<<endl;} } 对于上面两个成员重载函数,只有加了const修饰的对象才能调用第二个hello函数。 Object& hello() { num = 10; std::cout << "hello" << std::endl; return *this; } const Object& hello()const//返回常量对象,为了防止对象被修改,所以函数最前面还要加上const { std::cout << "word" << std::endl; return *this; } int main() { Object p1; const Object p2; Object&a=p1.hello();//第一个 const Object&a=p2.hello();//第二个 //上面两个都不开辟空间,都只是别名; 如果: Object a=p1.hello();//第一个 const Object a=p2.hello();//第二个 Object a=p2.hello()//调用拷贝构造函数,虽然p2.hello()是const的引用,但是对象a是普通对象,所以拷贝完 //后依旧是普通对象 } const修饰距离他最近的类型,所以如 template<typename T> int findValue(T arr[], int size, const T &val) 在模板特例化后参数的模板函数为: template<> int findValue<const char*>(const char* arr[], int size, const char* const &val) 在这里原模板的第三个参数类型式const T &val 这时const修饰的式T类型 所以在特例化后除了类型变为了const char* 还要保证const所修饰的类型不变 这里还涉及了#define和typedef的区别: 如#define T int* typedef int* T; 这两种替换发生在不同的时期,前者发生在预编译时期,后者发生在编译期 所以如果存在两条语句为: const T flag;//#define 由于这是宏替换所以在预编译完毕时,代码变为了: const int* flag 而距离const最近的类型为int所以const修饰的 是*flag,所以它的作用就是*flag可以改变,而flag可以改变 const T flag//typedef 而这个宏替换后产生了新的类型,T是不可以拆分的 const T flag ,const修饰的是T,也即是修饰的是int* 所以产生的结果就是const修饰的是flag,也就是flag可以改变但是*flag不能改变

最后

以上就是感性白云最近收集整理的关于const成员和对象的全部内容,更多相关const成员和对象内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部