C++ 当对象封装在const类中时,如何使用该对象的访问器方法?

C++ 当对象封装在const类中时,如何使用该对象的访问器方法?,c++,class,constants,operator-overloading,accessor,C++,Class,Constants,Operator Overloading,Accessor,让我更清楚地提出这个问题 我有一个Datarow对象: Class Datarow { private: vector<string> vals; public: std::string getVal(int index); //returns vals.at(index) }; 类数据行{ 私人: 向量VAL; 公众: std::string getVal(int-index);//返回vals.at(ind

让我更清楚地提出这个问题

我有一个Datarow对象:

 Class Datarow {
    private: 
      vector<string> vals;          

    public:

    std::string getVal(int index); //returns vals.at(index)
    };
类数据行{
私人:
向量VAL;
公众:
std::string getVal(int-index);//返回vals.at(index)
};
我有一个保存数据行的Section对象:

 Class Section {
    private: 
      vector<Datarow> rows;          

    public:
      //Section methods
    };
Class部分{
私人:
向量行;
公众:
//剖面法
};
我有一个超负荷:

 inline friend std::ostream& Section::operator<<(std::ostream& os, const Section& sec)
 {

   for(auto& row : sec.rows) {
       if( sec.row.getVal(0) == "Tom" )  //<-- error here, c++ doesnt like me calling any method of 
           os << row << endl;       // "row", since sec is const
   }  

 }
 

inline friend std::ostream&Section::operator正确的方法是将必要的
Datarow
方法转换为
const
方法,如下所示:

std::string getVal(int index) const;
                          //  ^^^^^   add this
friend std::ostream& operator<<(std::ostream& os, const Section& sec)
{
   // ...
}

现在,这些方法可以在
const
对象上调用,正如您在
操作符中所做的那样,这是一个令人尴尬的基础。谢谢你的帮助,不用担心,乐意帮忙:同时,如果你的答案是对你有用的话,你可以考虑接受这个答案。