常见错误 无法将this 从const type 转换为 非const type

错误原因:常量成员函数和常量对象不能调用非常量成员函数。

示例1:常量成员函数调用自身非常量成员函数

class Item
{
public:
    Item(string str):isbn(str){}
    void show() const{
        cout << this->book() << endl;
    }

    string book(){
        return this->isbn;
    }

private:
    string isbn;
};




int main(int argc, char *argv[])
{
    Q_UNUSED(argc);
    Q_UNUSED(argv);

    Item item("fan");
    item.show();

    return 0;

}

程序运行提示

cout << this->book() << endl; 

错误

book()成员函数改成以下定义则正确编译运行

string book() const{
        return this->isbn;
    }
示例2 定义常量对象,并调用非常量方法出错,同上的将book函数改成常量的则编译通过
class Item
{
public:
    Item(string str):isbn(str){}

    string book(){
        return this->isbn;
    }

private:
    string isbn;
};

int main(int argc, char *argv[])
{
    Q_UNUSED(argc);
    Q_UNUSED(argv);

    const Item item("fan");
    cout << item.book() << endl;

    return 0;

}

 

 

posted on 2017-03-09 13:05  Just_Boy  阅读(333)  评论(0编辑  收藏  举报