zoukankan      html  css  js  c++  java
  • C++中的error C2662,const的this指针问题

    今天在写C++代码的时候遇到一个错误,涉及到了常量的this指针的问题。

    简化后的代码如下:

    #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;
  • 相关阅读:
    Fiddler抓包
    用powershell Crescendo模块,把【linux字符命令】包装成【powershell对象命令】
    初探设计模式-单例模式
    dev的CheckedListBoxControl的使用
    git的安装及使用(三)----SSH连接
    go——杂碎小知识
    goland安装+打印hello world
    git的安装及使用(二)
    git的安装及使用(一)
    xxx
  • 原文地址:https://www.cnblogs.com/caiminfeng/p/4761433.html
Copyright © 2011-2022 走看看