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

C++ 如何调用以字符串数组为参数的特定构造函数?,c++,C++,在代码的int main()部分中调用类构造函数有点困难。 它是一个以字符串数组作为参数的构造函数 我知道,在调用构造函数时,可以设置默认参数,也可以不设置任何参数,并且需要一个对象来调用构造函数(以及我们想要给出的参数)。但我仍然不知道如何称呼它,尽管我尝试了许多不同的方法 这是我的代码: #include <iostream> #include <string> using namespace std; enum player_position{ GoalKeep

在代码的
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;
}
#包括
#包括
使用名称空间std;
enum球员位置{守门员、中场、后卫、前锋};
职业足球运动员
{
私人:
字符串名;
智力年龄;
积分;
球员位置Ppos;
公众:
足球运动员(字符串name=“aname”,内线年龄=20,内线积分=50,球员位置=前锋)
{
名称=_名称;
年龄=_年龄;
分数=_分;
Ppos=_-Ppos;
}
足球运动员(字符串str[4])/>str[0];
Name=str[0];

cout当您在第一个CTor中声明4个默认值时,您的呼叫
Football_Player object1(“梅西”)
将实际呼叫该CTor,然后离开

age = 20
points = 50
position = Striker
“要么必须给出所有参数,要么不给出参数”是完全错误的。对于所有参数,位置都很重要。在您的示例中:如果您给出两个参数,您就给出姓名和年龄。无法仅给出分数和位置。另外,像
Football\u Player object1(“梅西”,,中场);
这样的调用也是不可能的


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

以后,请用普通英语写,不要有点奇怪。调用使用4个字符串数组的构造函数环,您需要在主程序中使用一个包含4个字符串的数组才能传递给它。您还需要考虑如何将字符串
“Striker”
转换为枚举值
player\u position::Striker
。请注意
str[3]=Ppos;
将赋值颠倒,并且您没有在构造函数中设置
Age
Points
。坦率地说,调用它的困难表明它可能不是一个好的构造函数。
字符串strs[4]{“Name”、“num”、“num”、“pos”}另外,请注意,从下划线开始的名称实际上被保留用于“实现”,即C++编译器和运行时库。您应该在自己的代码中避免这样的名字。@ JonathanLeffler。非常感谢,先生,我已经理解了您所说的。STR〔3〕。=Ppos;也感谢您指出这一点..!!我以后将避免使用下划线命名..再次感谢。