C++中的error C2662,const的this指针问题
2015-08-26 19:22
471 查看
今天在写C++代码的时候遇到一个错误,涉及到了常量的this指针的问题。
简化后的代码如下:
这段代码在注释处会报编译错误如下:
报错提示无法将this指针由“const A”类型转为“A &”类型。
几番查找下得知问题在于代码中的print()函数被声明了为const的,C++在调用类成员函数时会隐式的传递this指针,而将函数声明为const即相当于this指针被声明为const的,如下:
这个声明相当于:
而这个被声明为const的this指针在print函数中调用getStr()时又会被传入,这里问题就出现了,getStr()函数并没有被声明为const的,那么这里面进行参数传递的时候就会发生类型不匹配的问题,也就是这里报的错误。
这里要清楚就是this指针的隐式传递,否则看到print()函数和getStr()函数都没有参数传递却报了这个错误就会感到莫名其妙,这也是我纠结了半天的问题。
解决的方法也很简单,将getStr()函数也声明为const的就可以了。
简化后的代码如下:
#include <iostream> #include <string> using namespace std; class A { private: string str; string getStr(); public: void print() const; }; string A::getStr() { return str; } void A::print() const { cout << getStr() << endl;//error here } int main() { A a; return 0; }
这段代码在注释处会报编译错误如下:
error C2662: 'std::string A::getStr(void)' : cannot convert 'this' pointer from 'const A' to 'A &'
报错提示无法将this指针由“const A”类型转为“A &”类型。
几番查找下得知问题在于代码中的print()函数被声明了为const的,C++在调用类成员函数时会隐式的传递this指针,而将函数声明为const即相当于this指针被声明为const的,如下:
void print() const;
这个声明相当于:
void print(const A * this);
而这个被声明为const的this指针在print函数中调用getStr()时又会被传入,这里问题就出现了,getStr()函数并没有被声明为const的,那么这里面进行参数传递的时候就会发生类型不匹配的问题,也就是这里报的错误。
这里要清楚就是this指针的隐式传递,否则看到print()函数和getStr()函数都没有参数传递却报了这个错误就会感到莫名其妙,这也是我纠结了半天的问题。
解决的方法也很简单,将getStr()函数也声明为const的就可以了。
string getStr() const;
相关文章推荐
- 关于const的底层实现
- 寻找距离某数最近的素数(C语言)
- C++的一道笔试题
- Thinking in C++之1.继承与组合概念、区别及优缺点
- c++ 时间类型详解 time_t
- 到C++11中的智能指针
- C++11新特性之Lambda函数
- Eclipse IDE for C/C++ Developers和MinGW安装配置C/C++开发学习环境详解
- c++-------------数组
- C++ primer 【笔记】C++中this指针的用法详解
- 【C++】阅读计划
- [C++11 并发编程] 11 - 线程间同步 - 等待一个消息或某种条件
- C++虚基类的作用
- 【黑马程序员】C语言-链表
- 论C++的静态联编和动态联编
- log4cpp之快速入门
- C语言各种数据类型在系统中占的字节和取值范围
- C语言基础知识之(七):循环嵌套的用途和规律
- C语言提供了几个标准库函数 itoa() atoi()
- C++虚函数与纯虚函数用法与区别(转)