3

重複の可能性:
引数のないコンストラクターに括弧がないことは言語標準ですか?

さて、私はピクルスを持っています。これはエラー C2228 の問題です。他の質問と回答を調べましたが、与えられたヒントはどれもうまくいかないようです。これは私の最初の質問であり、私は初心者なので、優しくしてください! 注:使用すると、プログラムはコンパイルされます

Wizard wiz0; 

しかし、私が使用する場合はそうではありません

Wizard wiz0();

私が使用している本では、これら 2 つのステートメントは等価であると書かれているため、一方を使用して他方を使用できない理由を理解しようとしています。

まず、ウィザード 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
}

ふぅ……これで全部だと思います。あなたが私が間違っていることを理解できるなら、私はそれを大いに感謝します!

4

2 に答える 2

6
Wizard wiz0;

Wizardと呼ばれるオブジェクトをインスタンス化しますwiz0

Wizard wiz0();

wiz0by値を返す関数を宣言しWizardます。これは、最も厄介な解析の簡略化されたバージョンです。

于 2012-10-19T12:51:04.187 に答える
3

これは、C++の解析方法の奇妙な部分です。括弧付きのものは関数プロトタイプとして解釈されます。かっこなしのものを使用する必要があります。

于 2012-10-19T12:50:56.317 に答える