【问题标题】:I cannot pass arguments to my class in c++我无法在 C++ 中将参数传递给我的类
【发布时间】:2021-12-20 11:03:05
【问题描述】:

我正在尝试将参数传递给我的班级,但它不起作用

#includes

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

类名和年龄是向量不要介意oldP这个函数

    class user{
        public:
        vector<string>Name;
        vector<int>Age;

    
    void outP() {

        for (unsigned int  i = 0; i < Name.size(); i++)
        {

            cout << Name[i] << " , ";

        }
    }
    user(vector<string> name, vector<int> age) {
        Name = name;
        Age = age;
    }

    


};

这是使用姓名和年龄并尝试将其传递给类的函数

    int holder() {
    string _name;
    int _age;

    int f = 0;



    while (true)
    {
        f++;

        cout << "enter name :";
        cin>>_name;

        cout << endl;

        cout << "enter age :";
        cin >> _age;



        if (f == 6)
        {
            break;

        }

    }

    user user1 = user(_name ,_age);


    
    return 0
}

当函数被调用时,程序会部分运行

【问题讨论】:

    标签: c++ class


    【解决方案1】:

    您的构造函数接受vector&lt;string&gt;vector&lt;int&gt; 类型的参数,但您尝试传入stringint 类型的值。由于没有从给定类型 T 到类型 vector&lt;T&gt; 的隐式转换,因此您需要纠正这种不匹配——要么更改构造函数接受的类型,要么更改您传递给的变量的类型构造函数。

    根据变量的名称,我猜你想完全摆脱vector...除非出于某种原因应该允许给定的user 有多个名称和多个年龄?

    【讨论】:

    • 我正在尝试存储多个用户数据
    • 在这种情况下,我建议让每个user 只包含一个string Name; 和一个int Age;,并声明一个vector&lt;user&gt; users; 来保存一组user 对象,每个@ 987654334@ 对象正好代表一个用户/人。 (请注意,为了使用vector&lt;user&gt;,您需要为您的用户类声明一个默认构造函数)
    • 如果你不介意给我你刚才所说的代码版本
    • 对不起,你得自己写代码,这就是你学习的方式:)
    • 所以我不需要使用类
    猜你喜欢
    • 1970-01-01
    • 2015-01-24
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多