gpt4 book ai didi

C++ 重载时的编译错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:10 24 4
gpt4 key购买 nike

以下代码可以正常编译。

#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;

关于C++ 重载时的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41422459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com