如何调用以字符串数组为参数的特定构造函数
How to call a specific constructor function that takes an array of strings as the argument?
我在代码的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个字符串组成的数组。没有更多,没有更少。但我建议删除那个,因为如果没有技巧,你也可以给它一个指向字符串的指针,从而导致崩溃。
相关文章:
- C++:使用运算符 = 调用多参数构造函数
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 好奇的混合与可变参数构造函数
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 为什么我们需要创建一个单参数构造函数来使用临时的无名称对象
- 在可变参数构造函数中初始化常量数组
- C++ 显式多参数构造函数歧义
- 零一参数构造函数
- 可变参数构造函数中的 SFINAE
- 当没有显式关键字与单参数构造函数一起使用时,编译器可以发出警告
- 可变参数类模板和可变参数构造函数
- 确保模板参数类型与其可变参数构造函数的类型匹配
- C++默认参数构造函数与内联初始化优先级
- 如何在 c++ 中将包含复制构造函数的类的参数构造函数称为私有?
- 自动存储中没有无参数构造函数的类对象和异常
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 如何在C++中调用无参数构造函数
- 在 c++ 中具有多个参数构造函数的模板类存在问题
- 可变参数构造函数优先于用户提供的移动构造函数,除非默认
- 如何从可变参数构造函数参数构造任何对象?