类不支持运算符

时间:2009-07-10 17:46:13

标签: c++ class operators

我从结构中创建了一个向量来存储多种类型的值。但是,我无法获得投入工作。

#include "std_lib_facilities.h"

struct People{
       string name;
       int age;
};

int main()
{
    vector<People>nameage;
    cout << "Enter name then age until done. Press enter, 0, enter to continue.:\n";
    People name;
    People age;
    while(name != "0"){
                 cin >> name;
                 nameage.push_back(name);
                 cin >> age;
                 nameage.push_back(age);}
    vector<People>::iterator i = (nameage.end()-1);
    nameage.erase(i);    
}

我也尝试在main函数中使用name和age变量为string / int类型,虽然这样可以解决运算符问题,但它会导致push_back行中函数调用的问题。

P.S。是否可以push_back多个输入,如...

cin >> name >> age;
nameage.push_back(name,age);

4 个答案:

答案 0 :(得分:8)

为什么不这样做:

People p;
cin >> p.name;
cin >> p.age;
nameage.push_back( p );

您不能只cin >> p,因为istream无法理解如何输入“人物”对象。因此,您可以为operator>>定义People,也可以将各个字段读入People对象。

另外,请注意,您需要push_back People类型的对象,因为这是您的vector - 它是People容器。

答案 1 :(得分:3)

一种选择是为人员定义operator>>

struct People
{
    friend std::istream & operator>> (std::istream & in, People & person);
};

std::istream & operator>> (std::istream & in, People & person)
{
    in >> person.name >> person.age;
    return in;
}

然后你可以写:

Person p;
cout << "Enter the person's name and age, separated by a space: ";
cin >> p;
nameage.push_back (p);

答案 2 :(得分:1)

你可能意味着:

People person;
while( cin >> person.name >> person.age && person.age != 0){
  nameage.push_back(person);
}

或者更好的是你可以重载&gt;&gt;运营商,但看起来你正在寻找一个更初学的解决方案。

答案 3 :(得分:0)

我认为你想在主()中将name声明为字符串并将age声明为int。您将它们声明为People。除非您重载了运算符&gt;&gt;。

,否则无法编译