【问题标题】:C++ - Insertion Operator, const Keyword Causes Compiler ErrorC++ - 插入运算符,const 关键字导致编译器错误
【发布时间】:2011-08-01 03:42:29
【问题描述】:

所以我正在构建一个类,为简单起见,我将在这里简化它。

这会导致编译器错误:“错误:对象具有与成员函数不兼容的类型限定符。”

这是代码:

ostream& operator<<(ostream& out, const Foo& f)
{
    for (int i = 0; i < f.size(); i++)
        out << f.at(i) << ", ";

    out << endl;
    return out;
}

at(int i) 函数从索引 i 处的数组返回一个值。

如果我从 Foo 中删除 const 关键字,一切都会很好。为什么?

编辑:根据请求,成员函数的声明。

.h

public:
    int size(void);
    int at(int);

.cpp

  int Foo::size()
    {
       return _size; //_size is a private int to keep track size of an array.
    }

    int Foo::at(int i)
    {
       return data[i]; //where data is an array, in this case of ints
    }

【问题讨论】:

  • Foo::atFoo::size 是如何声明的?

标签: c++ operator-overloading constants


【解决方案1】:

您需要将“at”函数和“size”函数声明为 const,否则它们无法作用于 const 对象。

所以,你的函数可能看起来像这样:

int Foo::at(int i)
{
     // whatever
}

它需要看起来像这样:

int Foo::at(int i) const
{
     // whatever
}

【讨论】:

  • 自从您引起我的注意以来,我一直在尝试查找这方面的信息,但我发现我的搜索效率有些低(通常会遍历关键字 const 的所有其他用途),通过你有没有关于它的参考?
  • @DivinusVox:当然,here ya go.
  • 如果你想谷歌了解更多信息,请尝试const member function c++
【解决方案2】:

您正在调用一个函数来更改常量对象上的对象。您必须确保函数at 不会更改类Foo 的对象,方法是将其声明为const(或删除参数中的const 以允许at 执行任何操作确实需要更改Foo中的一些内部数据)。

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 2019-04-06
    • 1970-01-01
    • 2014-02-08
    • 2017-06-05
    • 2012-08-13
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多