如何调用以字符串数组作为参数的特定构造函数?

时间:2014-09-28 22:18:06

标签: c++

我在代码的int main()部分调用类构造函数时遇到了一些困难。 它是一个构造函数,以字符串数组作为参数。

我知道,在调用构造函数时,可以设置默认参数或根本不设置参数,并且需要一个对象来调用构造函数(以及我们想要在其中提供的参数)。但我仍然不明白如何称呼它,尽管我尝试了很多不同的方法。

这是我的代码:

#include <iostream>
#include <string>

using namespace std;

enum player_position{ GoalKeeper, Midfielder, Defender, Striker };

class Football_Player
{
private:
    string Name;
    int Age;
    int Points;
    player_position Ppos;

public:
    Football_Player(string _name = "aname", int _age = 20, int _points = 50, player_position _ppos = Striker)
    {
        Name = _name;
        Age = _age;
        Points = _points;
        Ppos = _ppos;
    }

    Football_Player(string str[4])    // <---- "This Constructor is the one , i can't seem to call into the main()."
    {
        cin >> str[0];
        Name = str[0];
        cout << Name;
        cout << str[0];
        int a = atoi(str[1].c_str());
        cout << a;
        int b = atoi(str[2].c_str());
        cout << b;
        str[3] = Ppos;
    }
};

int main()
{

    // Please don't take any of the info as biased, these are just random.

    Football_Player("Messi", 20, 50, Striker);// This one is the previous constructor with the default arguments and this one seems to be working.  


    Football_Player ();    // Trying to call that constructor
    Football_Player object1("Messi");  // Trying to call that constructor
    Football_Player object2("Ronaldo", 25, 50, Striker);    // Again trying to call that Constructor
    Football_Player object3(str[0]);    // And Again . . . . 

    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:1)

当您在第一个CTor中声明了4个默认值时,您的通话Football_Player object1("Messi");实际上会调用该默认值,并离开

age = 20
points = 50
position = Striker

你要么“必须给所有参数,要么没有”,这是完全错误的。对于你给出的所有论点,位置很重要。在您的示例中:如果您提供2个参数,则提供名称和年龄。没有办法只给出分数和位置。此外,无法调用Football_Player object1("Messi",,,Midfield);这样的电话。

第二个构造函数总是需要一个包含4个字符串的数组。没有更多,没有更少。但我建议删除那个,因为没有技巧你也可以给它一个指向字符串的指针,导致崩溃。