嘿伙计,所以我正在研究一个基本程序,需要我们练习构造函数,但我不明白为什么我得到错误的输出.每当我运行代码时,我总是把bob作为我的输出而不是其他的bob.如果有人能告诉我我做错了什么以及如何解决它会很棒!
以下是我的.h文件:
#include <iostream>
#include <string>
using namespace std;
class creature{
public:
creature();
creature(int a);//initalizes the name of the creature based on what the user chooses(1,2, or 3 determines the monster name)
string getName();//accessor for the name
string getColor();//accessor for the color
private:
string name;
string color;
};
Run Code Online (Sandbox Code Playgroud)
以下是我的一个cpp文件:
creature::creature(){
name="bob";
color="black";
}
creature::creature(int a)
{
if(a==1)
name="bob_1";
else if(a==2)
name="bob_2";
else if(a==3)
name="bob_3";
}
string creature::getName()
{
return name;
}
Run Code Online (Sandbox Code Playgroud)
以下是我的一个cpp文件:
#include "creature.h"
int main()
{
creature monster;
int choice;
cout << "Enter 1 2 or 3 to choose your creature" << endl;
cin >> input;
if (input == 1)
{
creature(input);
cout << "Congratulations you have chosen " << monster.getName() <<;
}
else if (input == 2)
{
creature(choice);
cout << "Congratulations you have chosen " << monster.getName() <<;
}
else if (input == 3)
{
creature(input);
cout << "Congratulations you have chosen " << monster.getName() <<;
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码:
creature monster;
Run Code Online (Sandbox Code Playgroud)
使用无参数构造函数创建怪物.然后:
creature(choice);
Run Code Online (Sandbox Code Playgroud)
只是创建并立即摧毁同一类型的无名临时,但绝不会修改原始怪物.
你可能想要这样的东西:
monster = creature(choice);
Run Code Online (Sandbox Code Playgroud)
或者变量应该是一个指针,也许是一个聪明的指针:
std::unique_ptr<creature> monster;
...
monster.reset(new creature(choice));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |