为什么向导wiz0;不等于Wizard wiz0();在我的代码? C2228错误

时间:2012-10-19 12:49:05

标签: c++ compiler-errors visual-c++-2010-express

  

可能重复:
  Is no parentheses on a constructor with no arguments a language standard?

好的,我有一个泡菜。这是一个错误的C2228问题,我看了其他的问题和答案,并没有给出任何提示似乎对我有用 - 这是我的第一个问题,我是一个新手,所以请温柔!注意:如果我使用

,程序将编译
Wizard wiz0; 

但不是如果我使用

Wizard wiz0();

我使用的这本书告诉我这两个陈述应该是等价的,所以我试图找出为什么我可以使用一个而不是另一个。

首先,当我尝试使用向导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

这是(我认为)第5章的相关代码是:

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
}
P?......我认为这就是一切。如果你们能弄明白我做错了什么,我会非常感激!

2 个答案:

答案 0 :(得分:6)

Wizard wiz0;

实例化名为Wizard

wiz0对象
Wizard wiz0();

声明函数wiz0按值返回Wizard。这是most vexing parse的简化版。

答案 1 :(得分:3)

这是C ++解析方式的一个奇怪部分。带括号的那个被解释为函数原型。你应该使用没有括号的那个。