Soo*_*Soo 1 c++ overloading compiler-errors
以下代码编译正常.
#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;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我通过添加"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
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
我使用过"gcc version 4.8.4(Ubuntu 4.8.4-2ubuntu1~14.04.3)"
您不能定义具有相同名称的两个函数,这两个函数仅在返回类型上有所不同.因此,使用不同的名称定义函数,例如:
std::vector<int> getValueCopy() const;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
736 次 |
| 最近记录: |