【问题标题】:How to make use of an accessor method of an object when that object is encapsulated within a const class?当对象封装在 const 类中时,如何利用对象的访问器方法?
【发布时间】:2020-11-24 00:55:15
【问题描述】:

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

我有一个 Datarow 对象:

 Class Datarow {
    private: 
      vector<string> vals;          

    public:

    std::string getVal(int index); //returns vals.at(index)
    };

我有一个保存数据行的 Section 对象:

 Class Section {
    private: 
      vector<Datarow> rows;          

    public:
      //Section methods
    };

我有一个重载:

 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
   }  

 }
 

假设我们也为 Datarow 重载了

【问题讨论】:

    标签: c++ class constants operator-overloading accessor


    【解决方案1】:

    正确的做法是把必要的Datarow方法变成const方法,像这样:

    std::string getVal(int index) const;
                              //  ^^^^^   add this
    

    现在可以在 const 对象上调用这些方法,就像在 operator&lt;&lt; 中所做的那样。

    另外,您的operator&lt;&lt;friend 函数,不应使用Section:: 限定,如下所示:

    friend std::ostream& operator<<(std::ostream& os, const Section& sec)
    {
       // ...
    }
    

    另外,inline 关键字不会在此处添加任何有用的内容,因此您可以将其删除。

    【讨论】:

    • 这是令人尴尬的基础。谢谢你的帮助。
    • 不用担心,很乐意提供帮助 :) 另外,如果它最终对您有用,请考虑接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多