可能重复:
没有参数的构造函数上没有括号是语言标准吗?
好的,我有一个泡菜。这是一个错误 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
}
呼……我想这就是一切。如果你们能弄清楚我做错了什么,我将不胜感激!