gpt4 book ai didi

c++ - 名称隐藏在 C++ 中

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:16 25 4
gpt4 key购买 nike

#include<iostream>

using namespace std;

class ParentClass {
public:
virtual void someFunc(int a){
printf(" ParentClass :: someFunc (int) \n");
};

virtual void someFunc(int* a){
printf(" ParentClass :: someFunc (int*) \n");
};
};

class ChildClass : public ParentClass {
public:
virtual void someFunc(int* a){
printf(" ChildClass :: someFunc(int*) \n");
};
};

int main(){
ChildClass obj;
/* This function call results in an error: */
obj.someFunc(7);
}

第一个报错

tr2.cpp: In function 'int main()':
tr2.cpp:27:19: error: invalid conversion from 'int' to 'int*' [-fpermissive]
obj.someFunc(7);
^
tr2.cpp:18:18: error: initializing argument 1 of 'virtual void ChildClass::som
eFunc(int*)' [-fpermissive]
virtual void someFunc(int* a){
^

但是如果我们将方法更改为接受 char 而不是 int* 那么

#include<iostream>

using namespace std;

class ParentClass {
public:
virtual void someFunc(int a){
printf(" ParentClass :: someFunc (int) \n");
};

virtual void someFunc(char a){
printf(" ParentClass :: someFunc (char) \n");
};
};

class ChildClass : public ParentClass {
public:
virtual void someFunc(char a){
cout<<a<<endl;
printf(" ChildClass :: someFunc(char) \n");
};
};

int main(){
ChildClass obj;
/* This function call results in an error: */
obj.someFunc(7);
}

输出:

 ChildClass ::  someFunc(char)

伴随着windows的声音(叮)。 - ANS:此处为隐式转换。请检查下面的修改。

因此名称隐藏在第一个示例中起作用,但在第二个示例中不起作用。谁能解释为什么?我也尝试过使用不同数量的参数重载重写虚函数,例如int func(int a) , int func (int a, int b),然后只覆盖其中一个。在那种情况下,名称隐藏也不起作用,派生类能够派生未被覆盖的基类的虚函数。

为什么这个名称隐藏只适用于这种特殊情况?

编辑 1:

用 Context to Eternals 隐式转换的解释。我有另一个应该隐藏名称但没有隐藏的程序。在此版本中,方法根据不同的参数数量进行区分。

#include<iostream>

using namespace std;

class ABC
{ public:
ABC()
{
cout<<"Constructor ABC"<<endl;
}
virtual void meth1(int a);
virtual void meth2(int a, int b);
};

void ABC :: meth1(int a)
{
cout<<"One"<<endl;
}

void ABC:: meth2(int a, int b)
{
cout<<"Two"<<endl;
}

class BC:public ABC
{
public:
BC()
{
cout<<"Cons B"<<endl;
}

void meth1(int a);
};

void BC :: meth1(int a)
{
cout<<"Three"<<endl;
}

int main()
{
BC b;
b.meth1(5);
b.meth2(6,7);
}

输出:

C:\Users\Shaurya\Desktop>a
Constructor ABC
Cons B
Three
Two

名称隐藏在这种情况下也不起作用。

最佳答案

当您在 ChildClass 中重载 someFunc() 时,它会隐藏 ParentClass 的两个重载。在第一种情况下,您调用的函数将 int* 作为带有整数的参数,因此它当然会崩溃,因为它无法进行转换。

在第二种情况下,您正在调用一个函数,该函数将 char 作为带有整数的参数,因此存在隐式转换,一切都很好。

编辑 1 后更新:

我真的不明白你期望会发生什么:

  • 首先你构造一个 BC,它是 ABC 的 child ,所以调用 ABC 的构造函数然后 BC
  • 之后调用 meth1():因为 BC 覆盖了它,所以调用了 BC::meth1()
  • 最后你调用了 meth2():因为 BC 没有覆盖它,所以调用了 ABC::meth2()

这里发生的唯一“名称隐藏”是 BC 对 meth1 的覆盖,但它并没有真正隐藏任何东西......

关于c++ - 名称隐藏在 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26367216/

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