C ++我的程序只保留调用默认构造函数而不是带参数的构造函数

时间:2015-05-25 18:52:43

标签: c++ constructor

嘿伙计们所以我正在制作一个基本程序,要求我们练习构造函数,但我不明白为什么我得错了输出。每当我运行代码时,我总是把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;
  };

以下是我的一个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;
}

以下是我的一个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() <<;
    }

}

2 个答案:

答案 0 :(得分:5)

此代码:

creature monster;

使用无参数构造函数创建怪物。然后:

 creature(choice);

只是创建并立即销毁同一类型的无名临时,但绝不会修改原始怪物。

您可能需要以下内容:

monster = creature(choice);

或许变量应该是一个指针,也许是一个聪明的指针:

std::unique_ptr<creature> monster;
...
monster.reset(new creature(choice));

答案 1 :(得分:4)

您已在行

中创建了monster
creature monster;

使用默认构造函数。看起来你需要一个&#34;工厂&#34;按需创建生物的功能,否则

creature(input);

只是创建一个与原始monster无关的临时文件。在您的情况下,您还可以使用编译器生成的复制构造函数并编写

monster = creature(input); 

因此,您的原始monster正在重新分配新创建的。{/ p>

相关问题