英文:
I can't understand why one member function (A) is being called instead of another (D)
问题
我是C++的新手,我正在尝试理解我遇到的一些代码。
我的问题是为什么`a1->h()`调用了结构体`A`中的成员函数`h()`,而不是在结构体`D`中的那个。以下是代码:
```cpp
#include <iostream>
struct A{
int i;
A(int value) : i{value}{}
virtual int f() {return 1 + i;}
virtual int g() {return 2+ i;}
int h() {return 3+i;}
};
struct B : virtual A {
B() : A(10000) { }
int f() override { return 20; }
int h() { return 100+A::i; }
};
struct C : virtual A {
C() : A(-10) { }
int g() override { return 30; }
int h() { return 300+A::i; }
};
struct D : B, C {
D() : A(-5) { }
int h() { return 50+A::i; }
};
int main()
{
D d;
A *a1 = &d;
std::cout << a1->f() << ',' << a1->g() << ',' << a1->h()
<< '\n';
}
输出结果是:
20,30,-2
英文:
I'm new to C++ and I'm trying to understand some code I came across.
My question is why a1->h()
calls the member function h()
in struct A
instead of the one in struct D
. Here's the code below:
#include <iostream>
struct A{
int i;
A(int value) : i{value}{}
virtual int f() {return 1 + i;}
virtual int g() {return 2+ i;}
int h() {return 3+i;}
};
struct B : virtual A {
B() : A(10000) { }
int f() override { return 20; }
int h() { return 100+A::i; }
};
struct C : virtual A {
C() : A(-10) { }
int g() override { return 30; }
int h() { return 300+A::i; }
};
struct D : B, C {
D() : A(-5) { }
int h() { return 50+A::i; }
};
int main()
{
D d;
A *a1 = &d;
std::cout << a1->f() << ',' << a1->g() << ',' << a1->h()
<< '\n';
}
The output is:
20,30,-2
答案1
得分: 4
"由于你的基类 A 在 int h()
上没有使用 virtual
关键字,所以它不会被 D 重写。我相信将 virtual
添加到基类的 virtual int h()
将实现你想要的效果。"
英文:
Since your base class A does not have the virtual
keyword on int h()
then it will not be overriden by D. I believe adding virtual
to the base class virtual int h()
will achieve what you are looking for.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论