[Inheritance]Animal & Human问题总结

一开始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(){ ^

原因总结过来就是:

 const human & q = h;
    q.greeting();
这句话的“ const human & q = h;”q是h的引用,而且是const的,所以q 是const变量(那么对象也算是变量)而const变量只能调用const函数,所以我们写这个  greeting()函数时应该把它写成const 函数(我之前不明白的是为什么要把它写成const..而不是普通函数)
所以一开始的greeting()函数我应该写成const,而const函数只能访问const变量,于是乎,
string  _species;
string _name;
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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值