gpt4 book ai didi

c++ - 为什么 Sprite 是wiz0;不等同于向导 wiz0();在我的代码中? C2228 错误

转载 作者:太空狗 更新时间:2023-10-29 19:59:29 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Is no parentheses on a constructor with no arguments a language standard?

好吧,我有一个泡菜。这是一个错误 C2228 问题,我查看了其他问题和答案,但给出的提示似乎都不适合我 - 这是我的第一个问题,我是新手,所以请保持温柔!注意:如果我使用

,程序将编译
Wizard wiz0; 

但如果我使用则不会

Wizard wiz0();

我正在使用的书告诉我这两个陈述应该是等价的,所以我想弄清楚为什么我可以使用一个而不是另一个。

首先,这是我尝试使用 Wizard wiz0() 时的错误:

1>  Chapter5.cpp
1>Chapter5.cpp(14): error C2228: left of '.fight' must have class/struct/union
1>Chapter5.cpp(15): error C2228: left of '.talk' must have class/struct/union
1>Chapter5.cpp(17): error C2228: left of '.setArmor' must have class/struct/union
1>Chapter5.cpp(19): error C2228: left of '.getName' must have class/struct/union
1>Chapter5.cpp(21): error C2228: left of '.castSpell' must have class/struct/union

这是(我认为的)Chapter5.cpp 中的相关代码是:

Wizard wiz0(); //declares a variable (wiz0) of type Wizard.

wiz0.fight();
wiz0.talk();

wiz0.setArmor(10);

cout << "Player's Name: " << wiz0.getName() << endl;

wiz0.castSpell();

此外,这是来自 wiz.h 文件的信息:

public
//Constructor
Wizard();

//Overloaded Constructor
Wizard(std::string name, int hp, int mp, int armor);

//Destructor
~Wizard();

//Methods
void fight();
void talk();
void castSpell();
void setArmor(int mArmor);
std::string Wizard::getName();

private:
//Data members
std::string mName;
int mHitPoints;
int mMagicPoints;
int mArmor;

...最后,来自 wiz.cpp 文件的信息!

//Wiz.cpp implementation file

#include "stdAfx.h"
#include "wiz.h"
using namespace std;

//The Constructor call
Wizard::Wizard()
{
/*If the client calls a constructor without
specifying values, these will be the default
values that the program will use */
mName = "DefaultName";
mHitPoints = 1;
mMagicPoints = 1;
mArmor = 0;
}

Wizard::Wizard(std::string name, int hp, int mp, int armor)
{
//Client called constructor WITH values, so create an
//object with them.
mName = name;
mHitPoints = hp;
mMagicPoints = mp;
mArmor = armor;
}

void Wizard::fight()
{
cout << "Fighting." << endl;
}

void Wizard::talk()
{
cout << "Talking." << endl;
}

void Wizard::castSpell()
{
if (mMagicPoints < 4)
cout << "Casting spell." << endl;
else
cout << "Not enough MP!" << endl;
}

void Wizard::setArmor(int armor)
{
if(armor >= 0)
mArmor = armor;
}

std::string Wizard::getName()
{
return mName;
}

Wizard::~Wizard()
{
//Not using dynamic memory- nothing to clean
}

呼...我想就这些了。如果你们能弄清楚我做错了什么,我将不胜感激!

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com