C++之对象包含与成员函数不兼容的类型限定符---补充(5)《Effective C++》
来源:互联网 发布:果蝇优化算法 编辑:程序博客网 时间:2024/05/16 09:27
C++值对象那个包含与成员函数不兼容的类型限定符:
在上篇博客中,运行代码时候,由于没有对show函数添加const,结果突然报了一个错误:对象包含与成员函数不兼容的类型限定符,所以本篇博客进行一个快速补充!
在解释这个问题之前,我们先来看看如下代码,到底有什么问题呢?
#include <iostream>#include <string>using namespace std;class Base{public: Base(){ cout << "=====Base的构造函数=====" << endl; } Base(int aa, int bb) :a(aa), b(bb){ cout << "=====Base的构造函数=====" << endl; } void show(){ cout << a << " " << b << endl; } ~Base(){ cout << "=====Base的析构函数=====" << endl; }private: int a; int b;};void hello(const Base& b){ cout << endl; cout << "=====hello=====" << endl; b.show(); cout << "---------------" << endl;}int main(){ Base b(1, 2); hello(b); return 0;}
当上面的代码在运行的时候就可以发现,编译器报错啦!在hello函数中的b.show()报错,什么错误呢?对象包含与成员函数不兼容的类型限定符,这是几个意思?
如果我们将代码修改一下呢?在const函数中调用non-const函数,可以发现有什么问题呢?代码如下:
#include <iostream>#include <string>using namespace std;class Base{public: Base(){ cout << "=====Base的构造函数=====" << endl; } Base(int aa, int bb) :a(aa), b(bb){ cout << "=====Base的构造函数=====" << endl; } void show()const { cout << a << " " << b << endl; hello1(); } void hello1(){ cout << a << " " << b << endl; } ~Base(){ cout << "=====Base的析构函数=====" << endl; }private: int a; int b;};void hello(const Base& b){ cout << endl; cout << "=====hello=====" << endl; b.show(); cout << "---------------" << endl;}int main(){ Base b(1, 2); hello(b); return 0;}
Base类中的show函数中的hello1()函数报错了,什么错误呢?看一下:对象含有与成员 函数 “Base::hello” 不兼容的类型限定符,因为const函数中不能调用non-const函数。
总结了一下这种类型的错误,参照大家的博客,可以发现这种解释为:
1)const对象只能调用const函数;
2)如果const函数中不小心修改了类成员或者调用了非常量函数,编译器会找出这类错误。
参考博客:http://blog.csdn.net/wonengguwozai/article/details/51957077
阅读全文
0 0
- C++之对象包含与成员函数不兼容的类型限定符---补充(5)《Effective C++》
- C++问题,对象包含与成员函数不兼容的类型限定符
- C++问题,对象包含与成员函数不兼容的类型限定符
- C++之const对象只能调用const成员函数---补充(18)《More Effective C++》
- 《Effective C++》读书笔记之item45:运用成员函数模板接受所有兼容类型
- C++之运用成员模板接受所有兼容类型(45)---《Effective C++》
- C++之成员函数内存布局③---补充(13)《Effective C++》
- Effective C++:条款45:运用成员函数模板接受所有兼容类型
- C++之创建自定义类型的数组---补充(17)《Effective C++》
- C++类型转换操作符---补充(8)《Effective C++》
- C++之函数返回局部变量的初级探索---补充(3)《Effective C++》
- [翻译] Effective C++, 3rd Edition, Item 45: 用 member function templates(成员函数模板) 接受 "all compatible types"(“所有兼容类型”)
- C++之需要类型转换时请为模板定义非成员函数(46)---《Effective C++》
- 《Effective C++》读书笔记之item46:需要类型转换时请为模板定义非成员函数
- C语言的const类型限定符
- C语言的volatile类型限定符
- C语言的restrict类型限定符
- C++之析构函数和构造函数调用时间---补充(2)《Effective C++》
- vb.net版机房重构--DataGridView控件
- Deprecation Notice: The Composer\Package\LinkConstraint\LinkConstraintInterface interface is depreca
- 监控服务器程序,挂掉后自动重启
- 01--类型
- ssh用法及命令
- C++之对象包含与成员函数不兼容的类型限定符---补充(5)《Effective C++》
- Linux下深度解析history命令来显示曾执行过的命令
- html5 video 元素
- Keras + TensorFlow
- 数位dp hdu2089 ,4734,bzoj 1026
- 博客分类暗语
- 理解mysql_如何优雅的设计表结构
- 《Python自然语言处理》学习笔记-第一章
- ionic中ion-multi-picker报错Cannot find module 'ion-multi-picker'.以及ion-multi-picker用法