C++ 重载时的编译错误

标签 c++ compiler-errors overloading

以下代码可以正常编译。

#include <iostream>
#include <vector>
using namespace std;

class MyClass
{
public:
    MyClass()
    {
        x.resize(2);
        x[0] = 10;
        x[1] = 100;
    }
    std::vector<int> getValue()
    {
        return x;
    }
    const std::vector<int>& getValue() const
    {
        return x;
    }
private:
       std::vector<int> x;
};


int main()
{

    MyClass m;
    std::vector<int> y = m.getValue();
    for(int i=0; i<y.size(); i++)
    {
        std::cout<<y[i]<<std::endl;
    }

    const std::vector<int>& z = m.getValue();
    for(int i=0; i<z.size(); i++)
    {
        std::cout<<z[i]<<std::endl;
    }
    return 0;
}

但是,当我通过添加“const”(std::vector getValue() const) 将“std::vector getValue()”更改为更正确的版本(因为函数应该更改对象)时给出以下编译错误。

error: 'const std::vector<int>& MyClass::getValue() const' cannot be overloaded const std::vector<int>& getValue() const

为什么会这样?

我用过“gcc 版本 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)”

最佳答案

您不能定义两个仅返回类型不同的同名函数。所以用不同的名字定义函数,例如:

std::vector<int> getValueCopy() const;

关于C++ 重载时的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41422459/

相关文章:

c++ - 如何在 YAML 中发出以逗号分隔的列表

c++ - std::copy: operator= 未找到

assembly - 使用uVision ARM编译器的未知操作码 'CBZ'

c++ - 运算符重载逻辑问题

c++ - 在引用限定符上重载成员函数的用例是什么?

c++ - 无法使用 seekdir() 设置流位置

c++ - 关于C++0x中右值的问题

dictionary - 为什么这个字典功能不起作用

php - Eclipse PHP(PDT): App::make(Filesystem::class) = Syntax Error unexpected class

c++ - 模板类中重载函数的条件编译