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
原创粉丝点击