次のコードは正常にコンパイルされます。オーバーロード時の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;
}
しかし、(「CONST」(スタンダード::ベクトルのgetValueを添加することにより(関数はオブジェクトを変更することになっているので)私がより正しいバージョンへの「スタンダード::ベクトルのgetValue()」を変更したとき)const)次のコンパイルエラーが発生します。
error: 'const std::vector<int>& MyClass::getValue() const' cannot be overloaded const std::vector<int>& getValue() const
なぜですか?
私はあなたが戻り値の型が異なるだけで、同じ名前を持つ2つの関数を定義することはできません「gccのバージョン4.8.4(〜14.04.3 Ubuntuの4.8.4-2ubuntu1)」
私はよく分からないが、おそらく&リターンで(アドレス演算子)を通過します。Constのstd ::ベクトル&のgetValue()constは { リターンを&バツ; } –
コンパイルされていないバージョンを投稿してください。 –
@RSahu最初のコードは正しいです。ポストの後半に記載されている変更により、コード –