首页 > 解决方案 > 我无法在 C++ 中将参数传递给我的类

问题描述

我正在尝试将一个论点传递给我的班级,但它不起作用

#包括

#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

解决方案


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

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


推荐阅读