【问题标题】:How do I inherit a constructor from base class in CPP?如何从 CPP 中的基类继承构造函数?
【发布时间】: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++ inheritance constructor


【解决方案1】:

继承的正确语法是

Dog::Dog() : Animal()
{
}

Dog::Dog(int h, int a, int w, const std::string& dt) 
   : Animal(h, a, w), dogtype{dt}
{
}

因为Dog() 是一个空的构造函数,你可以用

Dog::Dog() = default

定义Animal 构造函数的正确方法是:

Animal::Animal()
   : Animal(0,0,0)
{
}

Animal::Animal(int h, int a, int w)
  : height{h}, age{a}, weight{w}
{
}

第一个使用delegate constructor,第二个使用构造函数initializer list

【讨论】:

  • 您可能想提及Initializer list
  • @ZachSal 请将其标记为已接受,答案对您来说很好
  • @Moia 非常感谢您的帮助。我打算买一本 cpp 书来帮助我更好地理解语法。如果你不介意我问,冒号到底是做什么的?另外,为什么使用 : Animal(0,0,0) 而不是我的方法更好?再次,非常感谢您的帮助。我想我已将您的回复标记为答案。
  • @ZachSal 阅读有关初始化列表的链接。使用委托构造函数更不容易出错。这样,只有一个构造函数是初始化的委托,而其他构造函数则引用它。如果您在其中任何一个中实现构造,则多个构造函数可能会导致意外的不同行为
【解决方案2】:

@Moia 已经有了初始化Dog 对象时应该使用的正确语法。

您的代码不起作用的原因是,当代码转到Animal::Animal(h, a, w) 时,您的Dog 的底层Animal 已经初始化。

事实上,当你进入构造函数的第一行时,你的类中的所有成员,包括你父类的所有成员都已经被初始化了。除非您像@Moia 提到的那样完成了初始化列表或委托构造函数,否则它们将被默认初始化。

在这里写Animal::Animal(h, a, w),你只是创建了一个临时的Animal对象,它永远不会被使用。

虽然您仍然可以更改 heightage 和其他内容(如果您为它们提供了 setter 函数),但最好使用初始化器列表,因为您不会先初始化它们,然后再更改他们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2015-12-02
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2011-05-31
    相关资源
    最近更新 更多