【问题标题】:Class containing vector of classes包含类的传染媒介类
【发布时间】:2016-06-15 20:18:56
【问题描述】:

我定义了两个类:

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 (  );

【问题讨论】:

  • 如果您不将向量存储在类中,还会发生这种情况吗?请养成先提取一个最小但完整的例子的习惯。

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


【解决方案1】:

改变一下

void printAtributes ( void );

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

正如您从 const 引用中明确要求的那样

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

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

【讨论】:

  • 哦,谢谢我以前也有过,但它仍然给我错误,但我也忘了在课堂上更改它。
  • 并且需要显式的const,因为const std::vector&lt;T&gt; 上的std::begin() 会产生const_iterator
猜你喜欢
  • 1970-01-01
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 2011-12-12
相关资源
最近更新 更多