您的位置:首页 > 编程语言 > C语言/C++

C++之对象包含与成员函数不兼容的类型限定符---补充(5)《Effective C++》

2017-07-22 17:12 483 查看

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
4000
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: