【发布时间】:2020-10-06 06:12:05
【问题描述】:
我正在尝试解决继承问题。我有一个基类 Animal,其参数为 int 身高、年龄和体重。我还有一个默认构造函数和一个带参数的构造函数。我有一个带有参数 dogType 的派生类 Dog 和一个带有来自 Animal 的参数和新参数 dogType 的构造函数。我的问题是,如何使用来自 Animal 的带参数的构造函数用于 Dog 类?这就是我尝试这样做的方式,但是,它不起作用。我将包括所有头文件和实现文件。非常感谢任何帮助!
#pragma once
#include <iostream>
#include <string>
class Animal
{
private:
int height;
int age;
int weight;
public:
Animal();
Animal(int h, int a, int w);
void print()const;
};
#include "Animal.h"
#include <iostream>
Animal::Animal()
{
height = 0;
age = 0;
weight = 0;
}
Animal::Animal(int h, int a, int w)
{
height = h;
age = a;
weight = w;
}
void Animal::print()const
{
std::cout << "Height:" << height << std::endl;
std::cout << "Age:" << age << std::endl;
std::cout << "Weight:" << weight << std::endl;
}
#pragma once
#include "Animal.h"
#include <iostream>
class Dog :
public Animal
{
private:
std::string dogType;
public:
Dog();
Dog(int h, int a, int w, std::string dt);
void print()const;
};
#include "Dog.h"
Dog::Dog()
{
}
Dog::Dog(int h, int a, int w, std::string dt)
{
Animal::Animal(h, a, w);
dogType = dt;
}
void Dog::print()const
{
Animal::print();
std::cout << "Dog Type:" << dogType << std::endl;
}
【问题讨论】:
-
阅读好C++ programming book。请参阅 this C++ reference 和 n3337 C++ 标准。在 github 和 gitlab 上查找 C++ 源代码示例,例如Qt - 我碰巧写了一些。如果您的 C++ 编译器是 GCC,请阅读其文档并将其调用为
g++ -Wall -Wextra -g。另见GDB
标签: c++ inheritance constructor