다음 코드는 정상적으로 컴파일됩니다.오버로드시 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
왜 그렇습니까?
I 당신은 반환 형식 만 다른 동일한 이름을 가진 두 개의 함수를 정의 할 수 없습니다 "GCC 버전 4.8.4 (~ 14.04.3 우분투 4.8.4-2ubuntu1)"
잘 모르겠어요하지만 어쩌면 대가로 & (주소 연산자)를 통과 : CONST 표준 : 및 getValue() const를 { 반환 벡터을 &엑스; } –
컴파일하지 않는 버전을 게시하십시오. –
@RSahu 첫 번째 코드가 정확합니다. 게시물의 설명 된 변경 사항이 코드 –