包含类向量的类

时间:2016-03-02 19:28:40

标签: c++ class c++11 object vector

我定义了两个类:

class Group
{
  public:
    Group ( void );
    bool addStudent ( const Student & X );
    void printAll( void ) const;

  protected:
    vector<Student> vectorOfStudents;
};
//-----------------------------------------------
class Student
{
   public:
     Student ( string name, int age );
     void printAtributes ( void );

   protected:
     string                    nameOfStudent;
     int                       ageOfStudent;
};

我正在创建对象并将它们存储在Group对象中以向量,但是当我想打印它时我有问题:

void Group::printAll ( void ) const
{
  for ( const auto &  student : vectorOfStudents )
  {
    student . printAtributes (  ); // Line 54
    cout << endl;
  }
}

以下是每次都应该打电话打印学生姓名的功能:

void Student::printAtributes ( void )
{
  cout << "name: " << nameOfStudent << " | " << "age: " << ageOfStudent<< endl;
}

给我这个错误:

54:33: error: passing ‘const Student’ as ‘this’ argument of ‘void Student::printAtributes()’ discards qualifiers [-fpermissive]
     student . printAtributes (  );

1 个答案:

答案 0 :(得分:1)

只需更改

void printAtributes ( void );

void printAtributes ( void ) const;
                          // ^^^^^

因为你明确要求它来自const引用

for ( const auto &  student : vectorOfStudents )
   // ^^^^^^^^^^^^

必须将函数声明为可从const引用调用。