一开始main.cpp里的下面两句总是报错
const human & q = h;
q.greeting();
报错信息:
main.cpp: In function 'int main()':main.cpp:17:16: error: passing 'const human' as 'this' argument discards qualifiers [-fpermissive] q.greeting(); ^In file included from main.cpp:4:0:human.h:33:6: note: in call to 'void human::greeting()' void human::greeting(){ ^
原因总结过来就是:
q.greeting();
这句话的“ const human & q = h;”q是h的引用,而且是const的,所以q 是const变量(那么对象也算是变量)而const变量只能调用const函数,所以我们写这个 greeting()函数时应该把它写成const 函数(我之前不明白的是为什么要把它写成const..而不是普通函数)
int _eyes;需要全部改成const变量,因此,到了最后不止greeting()函数应该写成const,还有print_eyes()也需要,因为里面访问的数据域也是const的,所以它也要变成const 函数。
Description
First, write a base class animal in animal.h, which has 2 attributes: string _species and int _eyes. This class should also have a method: void printeyes(), which can printf "species has _eyes eyes." on screen.
Then, you are required to write a human class which is an inheritance class of animal. Its _species should always be "Human" and of course we have 2 eyes. The human class has an extra attribute: string _name. And it is able to say hello to us with an extra method, void greeting() : "Hello, I'm _name."
以及已经给出来的 mian.cpp:
#include <iostream>
#include <string>
#include "animal.h"
#include "human.h"
int main() {
std::string s, n;
int e;
std::cin >> s >> e >> n;
animal * p = new animal(s, e);
p->print_eyes();
delete p;
human h(n);
p = &h;
p->print_eyes();
const human & q = h;
q.greeting();
return 0;
}