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

How to call a specific constructor function that takes an array of strings as the argument?

本文关键字:参数 构造函数 数组 字符串 何调用 调用      更新时间:2023-10-16

我在代码的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;
}

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

age = 20
points = 50
position = Striker

你"要么必须给出所有参数,要么不给出",这是完全错误的。对于你提出的所有论点,立场都很重要。在你的例子中:如果你给出两个论点,你会给出名字和年龄。没有办法只给出分数和位置。同样,像Football_Player object1("Messi",,,Midfield);这样的呼叫是不可能的。

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