代码之家  ›  专栏  ›  技术社区  ›  Steve

从常量成员函数调用非常量成员函数

  •  14
  • Steve  · 技术社区  · 14 年前

    我想知道是否可以从const成员函数调用非const成员函数。在下面的例子中,首先给出一个编译器错误。我明白为什么会出错,我想知道是否有办法解决这个问题。

    class Foo
    {
       const int& First() const
       {
             return Second();
       }
    
       int& Second()
       {
            return m_bar;
       }
    
       int m_bar;
    }
    

    我真的不想讨论这样做是否明智,我很好奇是否有可能。

    7 回复  |  直到 14 年前
        1
  •  32
  •   Adam Wright    14 年前
    return (const_cast<Foo*>(this))->Second();
    

    然后哭泣,安静。

        2
  •  10
  •   James McNellis    14 年前

    它是 可能的

    const int& First() const 
    { 
        return const_cast<Foo*>(this)->Second(); 
    }
    
    int& Second() { return m_bar; }
    

    我不建议这么做,因为它既丑陋又危险 const_cast 是危险的)。

    对于这样一个简单的访问器,可以很容易地 return m_bar; 从两个函数调用一个函数。

        3
  •  3
  •   Mark Ransom    14 年前

    根据定义 const

    我知道你说过你不想听这个,但我认为这对其他人来说很重要。

        4
  •  3
  •   Jack Wu    10 年前

    class CFoo
    { 
    public:
        CFoo() {m_Foo = this;}
        void tee();
    
        void bar() const 
        { 
            m_Foo->m_val++;  // fine 
            m_Foo->tee();    // fine
        }
    private:
       CFoo * m_Foo;
       int    m_Val;  
    
    };
    

    这实际上取消了const成员函数的目的,所以在设计新类时最好不要这样做。知道有一种方法可以做到这一点是没有坏处的,特别是它可以被用来解决这些在const成员函数概念上设计得不好的旧类。

        5
  •  2
  •   Fred Larson    14 年前

    const :

    const int& Second() const
    {
        return m_bar;
    }
    

        6
  •  1
  •   Greg Domjan    14 年前

    迭代器在这方面是相似的,并且做了一个有趣的研究。

    const迭代器通常是“非const”迭代器的基础,您将经常发现 const_cast<>() 或C样式的强制转换,用于从基类中丢弃子类中具有访问器的常量。

    编辑:

    我有一个zip迭代器,其中const从非const继承

    这通常是错误的继承结构(如果你说的是我认为你是什么),原因是孩子不应该比父母少限制。

    假设你有一个带zip迭代器的算法,那么把一个const迭代器传递给一个非const是否合适?

    class ConstIterator: 
        public std::_Bidit< myType, int, const myType *, const mType & >
    {
      reference operator*() const { return m_p; }
    }
    
    class Iterator : public ConstIterator 
    {
      typedef ConstIterator _Mybase;
      // overide the types provided by ConstIterator
      typedef myType * pointer;
      typedef myType & reference;
    
      reference operator*() const
      { 
        return ((reference)**(_Mybase *)this);
      }
    }
    
    typedef std::reverse_iterator<ConstIterator> ConstReverseIterator;
    typedef std::reverse_iterator<Iterator> ReverseIterator;
    
        7
  •  0
  •   sage    12 年前

    我发现自己试图调用继承的非const成员函数,但实际上是const,因为我正在使用的API。最后,我决定了一个不同的解决方案:重新协商API,使我继承的函数正确地常量。