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

Why is Wizard wiz0; not equivalent to Wizard wiz0(); in my code? C2228 Error

本文关键字:Wiz0 向导 错误 代码 C2228 不等于 为什么 我的      更新时间:2023-10-16

可能的重复:
没有辩论的构造函数上没有语言标准的括号?

好吧,我有泡菜。这是一个错误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.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
}

ph ...我认为这就是一切。如果你们能弄清楚我做错了什么,我会非常感谢!

Wizard wiz0;

实例化一个称为 wiz0

Wizard对象
Wizard wiz0();

声明函数wiz0返回 Wizard乘值。这是最烦人的解析的简化版本。

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