gpt4 book ai didi

c++ - 返回类型和参数列表都更改时隐藏名称

转载 作者:行者123 更新时间:2023-11-28 02:07:43 26 4
gpt4 key购买 nike

我的基本问题是为什么当返回类型和参数列表都改变时名称隐藏不适用。请引用下面的样本。

// Example program
#include <iostream>
#include <string>
using namespace std;

class base {
public:
int f() const { cout <<"I am base void version. "<<endl; return 1;}
int f(string) const { cout <<"I am base string version. "<<endl; return 1;}
};

class Derived1 : public base {
public:
int f() const {
cout << "Derived1::f()\n";
return 2;
}
};

class Derived2 : public base {
public:
int f(int) const {
cout << "Derived2::f()\n";
return 3;
}
};

class Derived3 : public base {
public:
void f(int) const {
cout << "Derived3::f()\n";
}
};


int main()
{
string s("hello");
Derived1 d1;
int x = d1.f();
//d1.f(s); // string version hidden

Derived2 d2;
//x = d2.f(); // f() version hidden
x = d2.f(1);

Derived3 d3;
d3.f(1); // No name hiding
}

输出:

Derived1::f()

Derived2::f()

Derived3::f()

在上面的程序中

a) 为什么不为 Derived2 对象隐藏字符串版本?

b) 为什么当返回类型和参数都匹配时名称隐藏不适用?

“名称隐藏在编译器级别如何工作?”的任何链接或引用资料很有用。

谢谢。

最佳答案

来自 Bjarne Stroustrup 自己的 FAQ on this subject :

Why doesn't overloading work for derived classes?

That question (in many variations) are usually prompted by an example like this:

#include<iostream>
using namespace std;

class B {
public:
int f(int i) { cout << "f(int): "; return i+1; }
// ...
};

class D : public B {
public:
double f(double d) { cout << "f(double): "; return d+1.3; }
// ...
};

int main()
{
D* pd = new D;

cout << pd->f(2) << '\n';
cout << pd->f(2.3) << '\n';
}

which will produce:

  f(double): 3.3
f(double): 3.6

rather than the

  f(int): 3
f(double): 3.6

that some people (wrongly) guessed.

您可以修改问题中的程序,通过将 using base::f; 添加到派生类来使隐藏的重载可用:

#include <iostream>
#include <string>
using namespace std;

class base {
public:
int f() const { cout <<"I am base int version. "<<endl; return 1; }
int f(string) const { cout <<"I am base string version. "<<endl; return 1; }
};

class Derived1 : public base {
public:
using base::f;
int f() const
{
cout << "Derived1::f()\n";
return 2;
}
};

class Derived2 : public base {
public:
using base::f;
int f(int) const
{
cout << "Derived2::f()\n";
return 3;
}
};

class Derived3 : public base {
public:

void f(int) const
{
cout << "Derived3::f()\n";
}
};


int main()
{
string s("hello");
Derived1 d1;
int x = d1.f();
d1.f(s); // string version hidden

Derived2 d2;
x = d2.f(); // f() version hidden
x = d2.f(1);

Derived3 d3;
d3.f(1); // No name hiding
}

然后输出是:

Derived1::f()
I am base string version.
I am base int version.
Derived2::f()
Derived3::f()

关于c++ - 返回类型和参数列表都更改时隐藏名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36853735/

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