简体   繁体   English

从派生类对象调用基类函数。 在派生类构造函数中设置的基类数据成员

[英]Calling a base class function from a derived class object. Base class data members set in derived class constructor

I have looked for the solution to the problem below all over the internet. 我一直在互联网上寻找问题的解决方案。 Some of the solutions given are exactly what I am doing, yet I am still getting an error when I try to compile my code. 给出的一些解决方案正是我正在做的事情,但是在尝试编译代码时仍然出现错误。 Any help would be greatly appreciated. 任何帮助将不胜感激。

I have a base class Stats that every monster class in my code will be derived from. 我有一个基类统计信息,我代码中的每个怪物类都会派生自该类。 Here is the base class: 这是基类:

#include <iostream>

class Stats {
    private:
        int hitpoints;
        int armor;
        int bonus;
    public:
        int getHP(){return hitpoints;}
        int getArm(){return armor;}
        int getBonus(){return bonus;}
        Stats();
        Stats(int, int, int);
};

Stats::Stats() {
    hitpoints = 0;
    armor = 0;
    bonus = 0;
}

Stats::Stats(int hp, int arm, int bon) {
    hitpoints = hp;
    armor = arm;
    bonus = bon;
}

Now I have a monster class (here Orc), that is derived from the Stats class. 现在我有一个怪物类(这里是兽人),它是从Stats类派生的。 The constructor of the monster class also calls the overloaded constructor of the Stats class: monster类的构造函数还调用Stats类的重载构造函数:

#include <iostream>
#include "Stats.cpp"

class Orc: public Stats {
    public:
        Orc();
};

Orc::Orc() : Stats(8, 3, 1) {}

In the main function I build a new Orc object and try to call the base class function Stats::getArm() with the object: 在主函数中,我建立一个新的Orc对象,并尝试使用该对象调用基类函数Stats :: getArm():

int main() {
    Orc mork();
    std::cout << "Armor: " << mork.Stats::getArm() << "\n";
}

I expect to have the function return the int value for armor. 我希望该函数返回盔甲的int值。 Instead I am getting the error: 相反,我得到了错误:

error: request for member 'Stats:: getArm' in 'mork', which is of a non-class type 'Orc()' 错误:请求“成员”中的成员“ Stats :: getArm”,该成员属于非类类型“ Orc()”

By the way, I am compiling in c++11. 顺便说一下,我正在c ++ 11中进行编译。

Orc mork();

This line does not do what you think it does. 此行不执行您认为的操作。 You meant to type: 您打算输入:

Orc mork;

Which would declare an Orc object named mork . 它将声明一个名为morkOrc对象。 Instead, you declared a function named mork that takes no arguments and returns an Orc . 相反,您声明了一个名为mork的函数,该函数不带任何参数并返回Orc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM