以下代码编译正常。C++编译过载错误
#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;
}
然而,当我改变“的std ::矢量的getValue()”到更正确的版本(因为该函数应该改变对象)加入“常量”(标准::矢量的getValue( )const)它给出了下面的编译错误。
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 ::矢量及的getValue()const的 { 回报&X; } –
发布不能编译的版本。 –
@RSahu第一个代码是正确的,后面所述的变更在发布后会打破代码 –