为什么我不能在类向量上使用任何向量函数,如push_back()或empty(),即使我在我的cpp文件中包含了<vector>?

问题描述 投票:0回答:1
#include "student.cpp"
#include <iostream>
#include <vector>
using namespace std;

vector<Student> studentcount;

class Student
{
private:
    string id;
    string firstname;
    string lastname;
    string address;
    string email;

public:
    Student()   //Default constructor
    {
        id = " ";
        firstname = " ";
        lastname = " ";
        address = " ";
        email = " ";
    }

    Student(string i, string f, string l, string a, string e);
};

int main()
{
    string i,f,l,a,e;
    cout<<"Please state your ID, first name, last name, address and email (seperated by a space in between).";
    cin>>i>>f>>l>>a>>e;
    Student student(i, f, l, a, e);    //declared the student class on its header file
    studentcount.push_back(student);
}

类“std::vector>”没有成员“push_back” 我似乎无法使用向量函数 当我使用空函数时,它也会带来问题,是否有我忘记添加的包含内容?谢谢你

c++ vector visual-c++ push-back
1个回答
0
投票

我不知道包含文件中有什么,但它是这样工作的。我删除了 cin 线以进行更好的测试,您可以将其恢复。你的构造函数很奇怪,使用初始化列表,并将向量放在类声明之后,而不是之前。

#include <iostream>
#include <vector>
using namespace std;

class Student
{

  public:
    Student(std::string id, std::string firstname, std::string lastname, std::string address, std::string email)
        : id(id), firstname(firstname), lastname(lastname), address(address), email(email)
    {
    }

  private:
    string id;
    string firstname;
    string lastname;
    string address;
    string email;

  public:
    void print_em_all()
    {
        std::cout << id << std::endl;
        std::cout << firstname << std::endl;
        std::cout << lastname << std::endl;
        std::cout << address << std::endl;
        std::cout << email << std::endl;
    }
};
vector<Student> studentcount;

int main()
{
    string i, f, l, a, e;
    i = "1";
    f = "Hans";
    l = "Chen";
    a = "123 street";
    e = "hanschen";
    Student student{i, f, l, a, e};
    studentcount.push_back(student);
    studentcount[0].print_em_all();
}
© www.soinside.com 2019 - 2024. All rights reserved.