【问题标题】:error C2228: left of '.printStats' must have class/struct/union错误 C2228:“.printStats”的左侧必须有类/结构/联合
【发布时间】:2015-03-30 07:27:24
【问题描述】:

所以我最近决定重新学习编程并使用 C++。尝试制作冒险者课程,但我似乎遇到了一些麻烦。这是我的文件:

Adventurer.h:

#ifndef __Adventurer_H_INCLUDED__   //if Adventurer.h hasn't been included yet...
#define __Adventurer_H_INCLUDED__   //#define this so the compiler knows it has been included

class Adventurer
{

    private:

        int hp, mp, str, agi, magic, armour;

    public:

        Adventurer(){}
        void printStats();

}

#endif

Adventurer.cpp:

#include <iostream>
#include "Adventurer.h"



Adventurer::Adventurer()
{

    hp = 50;
    mp = 25;
    str = 5;
    agi = 5;
    magic = 5;
    armour = 5;
}

void Adventurer::printStats()
{

    cout << "HP = " << hp << "\n\n";
    cout << "MP = " << mp << "\n\n";
    cout << "str = " << str << "\n\n";
    cout << "agi = " << agi << "\n\n";
    cout << "magic = " << magic << "\n\n";
    cout << "armour = " << armour << "\n\n";
}

RPG_Game.cpp:

// my first program in C++
#include <iostream>
#include <string>
#include "Adventurer.h"

;using namespace std;

int main()
{
    cout << "Hello Adventurer! What is your name? \n";
    string advName;
    cin >> advName;
    cout << "\nYour name is " << advName << "!";
    Adventurer *adv = new Adventurer();
    cout << adv.printStats();
    delete adv;
    system(pause);
}

【问题讨论】:

  • 拿起Good book 并阅读它,这是一个相当基本的错误 - 您在指针上使用了错误的运算符。

标签: c++


【解决方案1】:

让我们看看你的代码中的错误

首先,在您的 Adventurer.h 中,在类后面加上一个分号 (;)。

接下来,在同一堂课中,你有

Adventurer(){}

把这个改成

Adventurer();

然后,在你的 RPG_Game.cpp 中,改变

cout << adv.printStats();

adv->printStats() ;

使用指针时,需要使用-&gt;而不是.

最后,

system(pause);

应该是

system( "pause" );

现在,尝试运行您的代码。

另外,您可能会发现 this 很有帮助。

【讨论】:

  • 非常感谢。正如你所知道的那样,它仍然非常新,而且有很多 java 而不是 C++ 语言。感谢您更正我的代码并帮助我。我可能不知道为什么正在做的事情的确切原因,但至少现在我知道我可以查看某些领域以进一步掌握。再次感谢您!
猜你喜欢
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
相关资源
最近更新 更多