0

当我将一个对象传递给一个函数时,我得到了不想要的结果。Character当我通过aMage的 action() 函数时,似乎会发生这种情况。

以下是我的代码的一些片段:

字符.h

    class Character {
    public:
        Character();
        int getMaxLives() const;
        int getMaxCraft() const;

    protected:
        maxLives;
        maxCraft;
    };

字符.cpp

    #include "character.h"

    Character::Character () {
        maxLives = 5;
        MaxCraft = 10;
    }

    int Character::getMaxLives() const {
        return maxLives;
    }

    int Character::getMaxCraft() const {
        return maxCraft;
    }

法师.h

    #include "character.h"

    class Mage {
    public:
        Mage();
        void action(Character c1);
    };

魔法师.cpp

    #include "mage.h"   

    Mage::Mage () { ... }
    void Mage::action(Character c1) {
        cout << "Max Craft: " << c1.getMaxCraft() << endl;
        cout << "Max Lives: " << c1.getMaxLives() << endl; 
    }

驱动程序.cpp

    int main () {
        Character c1;
        Mage m1;

        m1.action(c1);

我的输出给了我以下信息:

Max Craft:728798402(数量不同)

最大生命:5


但是,如果在我的潜水员中,我会:

cout << "Max Craft: " << c1.getMaxCraft() << endl;
cout << "Max Lives: " << c1.getMaxLives() << endl; 

我得到:

最大工艺:10

最大生命:5

有任何想法吗?

4

1 回答 1

4

看起来你的意思是MaxCraft = 10;(在你的默认构造函数中)实际上是maxCraft = 10;. 正如@chris 在评论中所说,您似乎正在使用一些允许隐式类型变量的(邪恶的,邪恶的)C++ 扩展,因此该MaxCraft = 10;行只是定义了一个名为MaxCraft.

于 2012-12-08T20:20:58.787 回答