qq_45735316
2020-05-22 22:20
采纳率: 91.6%
浏览 236

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

图片说明
//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();虽然不会报错,但不能实现多态。

    已采纳该答案
    打赏 评论
  • UFO_SERIESOFSOFT 2020-05-23 08:50

    对象要实例话后才能使用,你的Box没有实例化

    打赏 评论

相关推荐 更多相似问题