gpt4 book ai didi

C++:方法重载的奇怪行为

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

我需要解释为什么以下代码无法编译。我有一个解决方法,我将在下面阐述,但我不明白原始版本的失败。

为了加快代码阅读:这个概念是定义一个接口(interface)(ISomething),然后创建一个抽象实现(ASomething)来实现第二个函数(2) 使用第一个(尚未定义)(1)。派生自抽象方法的完整实现(例如 SomethingImpl)必须定义第一个方法并可以选择覆盖第二个方法。

#include <iostream>

class ISomething
{
public:
virtual ~ISomething()
{ }
virtual int f(int x) = 0; // (1)
virtual int f(int x, int y) = 0; // (2)
};

class ASomething
: public virtual ISomething
{
public:
virtual int f(int x, int y) // (2)
{
return f(x) + f(y); // (3)
}
};

class SomethingImpl
: public ASomething
{
public:
virtual int f(int x) // (1)
{
return x+1;
}
};

int main()
{
SomethingImpl a;
std::cout << a.f(10) << std::endl; // (1)
std::cout << a.f(10,20) << std::endl; // (2)
return 0;
}

编译此代码会在 Visual Studio 2013 (Windows) 和 g++ 4.4.5 (Linux) 上出错。错误非常相似,我将仅详细介绍 g++ 输出:

$ g++     SibFun.cpp   -o SibFun
SibFun.cpp: In member function ‘virtual int ASomething::f(int, int)’:
SibFun.cpp:18: error: no matching function for call to ‘ASomething::f(int&)’
SibFun.cpp:16: note: candidates are: virtual int ASomething::f(int, int)
SibFun.cpp:18: error: no matching function for call to ‘ASomething::f(int&)’
SibFun.cpp:16: note: candidates are: virtual int ASomething::f(int, int)
SibFun.cpp: In function ‘int main()’:
SibFun.cpp:36: error: no matching function for call to ‘SomethingImpl::f(int, int)’
SibFun.cpp:26: note: candidates are: virtual int SomethingImpl::f(int)
make: *** [SibFun] Error 1

我尝试在 (3) 中使用不同的符号,例如 return this->f(x) + this->f(y),但我没有遇到任何显着的问题更改错误消息。

然而,当我将 (3) 更改为 return ISomething::f(x) + ISomething::f(y); 我只得到:

$ g++     SibFun.cpp   -o SibFun
SibFun.cpp: In function ‘int main()’:
SibFun.cpp:36: error: no matching function for call to ‘SomethingImpl::f(int, int)’
SibFun.cpp:26: note: candidates are: virtual int SomethingImpl::f(int)
make: *** [SibFun] Error 1

但是!当将 (2)f 更改为 g 时,所有编译和运行都按预期进行。

这种行为背后的原因是什么?为什么我不能为 (2) 使用 f 名称?

最佳答案

函数重载仅适用于同一范围内可见的函数:

class ASomething
: public virtual ISomething
{
public:
virtual int f(int x, int y) // (2)
{
return f(x) + f(y); // (3)
}

using ISomething::f;
//~~~~~~~~~~~~~~~~~^
};

class SomethingImpl
: public ASomething
{
public:
virtual int f(int x) // (1)
{
return x+1;
}

using ASomething::f;
//~~~~~~~~~~~~~~~~~^
};

关于C++:方法重载的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101704/

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