qq_45735316 2020-05-22 22:20 采纳率: 94.1%
浏览 248
已采纳

为什么会这样报错?编译的时候都没问题的

图片说明
//chapter7.10.cpp

/*定义一个Object类,有数据成员weight及其相应的操作函数,
由此派生出Box类,增加数据成员height和width及其相关1操作函数
声明一个Box类对象,观察构造函数与析构函数的调用顺序*/
#include <iostream>
#include "Classfile.h"
using namespace std;
int main()
{
    int weight, height, width;
    cin >> weight >> height >> width;
    Box b(weight,height,width);
    cout << b.getWeight()<<endl; 
    /*公有派生可以直接调用Object类的公有成员函数,
    不需要在派生类重新声明同名的成员*/
    cout << b.getHeight() << endl;
    cout << b.getWidth() << endl;
    cout << b.getV() << endl;
    return 0;
}

//Classfile.h

#pragma once
#include <iostream>
using namespace std;
class Object {
private:
    int weight;
public:
    Object(int weight = 0);
    int getWeight()const;
    ~Object();
};
class Box:public Object {
private:
    int height;
    int width;
public:
    Box(int weight=0, int height=0, int width=0);
    int getWeight()const;
    int getHeight()const;
    int getWidth()const;
    int getV()const;
    ~Box();
};

//Classfile.cpp

#include <iostream>
#include "Classfile.h"
using namespace std;
Object::Object(int weight) :weight(weight)
{
    cout << "calling the constructor of Object" << endl;
}
int Object::getWeight()const
{
    return weight;
}
Object::~Object() { cout << "calling the desctructor of Object" << endl; }
Box::Box(int weight, int height, int width) :Object(weight), height(height), width(width)
{
    cout << "calling the constructor of Box" << endl;
}
int Box::getHeight()const
{
    return height;
}
int Box::getWidth()const
{
    return width;
}
Box::~Box()
{
    cout << "calling the destructor of Box" << endl;
}
int Box::getV()const
{
    return Object::getWeight() * height * width;
}

  • 写回答

2条回答 默认 最新

  • qtchen_1988 2020-05-23 10:40
    关注

    只看到 Box::getWeight()的声明,没看到它的实现。还有跟父类重名的了,覆盖了父类的getWeight();虽然不会报错,但不能实现多态。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站