[英]C++ Compilation error in 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;
通過將const
添加到第一個函數中,您可以使對getValue
調用變得模棱兩可:這兩個函數之間有什么區別:
std::vector<int> getValue() const; // 1
const std::vector<int>& getValue() const; // 2
好吧,除了返回值外,它們都是一樣的,但是請稍等! 您不能基於C ++中的返回類型進行重載! 這沒有任何意義,大多數通話會模棱兩可:
std::vector<int> y = m.getValue(); // which one? It can be 1, it can be 2 (std::vector<int>
// is not a better match than const std::vector<int>&)
const std::vector<int>& z = m.getValue(); // same as above
m.getValue(); // which one?
但是,兩者之間的區別應該是什么?
第一個是100%安全的,而第二個則不是:一個可以存儲對x
引用,如果該對象被破壞,它將成為懸掛的引用。 所以我想說,如果可能的話,您可以擺脫第二個。
您的問題是您不了解函數重載概念
當重載函數時函數的定義必須因參數類型或參數列表中參數的數量而彼此不同。
您不能重載僅在返回類型上有所不同的函數聲明。
在您的職能中:
std::vector<int> getValue() const
const std::vector<int>& getValue() const
它僅在返回類型上有所不同,因此將不被視為重載函數
糾正錯誤的最佳方法是將第二個函數名稱更改為getValuev2()
或更改其中一個功能的參數。
您可以閱讀有關C ++中的重載的更多信息: https : //www.tutorialspoint.com/cplusplus/cpp_overloading.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.