我无法理解为什么会调用一个成员函数(A)而不是另一个(D)。

huangapple go评论77阅读模式
英文:

I can't understand why one member function (A) is being called instead of another (D)

问题

  1. 我是C++的新手,我正在尝试理解我遇到的一些代码。
  2. 我的问题是为什么`a1->h()`调用了结构体`A`中的成员函数`h()`,而不是在结构体`D`中的那个。以下是代码:
  3. ```cpp
  4. #include <iostream>
  5. struct A{
  6. int i;
  7. A(int value) : i{value}{}
  8. virtual int f() {return 1 + i;}
  9. virtual int g() {return 2+ i;}
  10. int h() {return 3+i;}
  11. };
  12. struct B : virtual A {
  13. B() : A(10000) { }
  14. int f() override { return 20; }
  15. int h() { return 100+A::i; }
  16. };
  17. struct C : virtual A {
  18. C() : A(-10) { }
  19. int g() override { return 30; }
  20. int h() { return 300+A::i; }
  21. };
  22. struct D : B, C {
  23. D() : A(-5) { }
  24. int h() { return 50+A::i; }
  25. };
  26. int main()
  27. {
  28. D d;
  29. A *a1 = &d;
  30. std::cout << a1->f() << ',' << a1->g() << ',' << a1->h()
  31. << '\n';
  32. }

输出结果是:

  1. 20,30,-2
英文:

I'm new to C++ and I'm trying to understand some code I came across.

My question is why a1-&gt;h() calls the member function h() in struct A instead of the one in struct D. Here's the code below:

  1. #include &lt;iostream&gt;
  2. struct A{
  3. int i;
  4. A(int value) : i{value}{}
  5. virtual int f() {return 1 + i;}
  6. virtual int g() {return 2+ i;}
  7. int h() {return 3+i;}
  8. };
  9. struct B : virtual A {
  10. B() : A(10000) { }
  11. int f() override { return 20; }
  12. int h() { return 100+A::i; }
  13. };
  14. struct C : virtual A {
  15. C() : A(-10) { }
  16. int g() override { return 30; }
  17. int h() { return 300+A::i; }
  18. };
  19. struct D : B, C {
  20. D() : A(-5) { }
  21. int h() { return 50+A::i; }
  22. };
  23. int main()
  24. {
  25. D d;
  26. A *a1 = &amp;d;
  27. std::cout &lt;&lt; a1-&gt;f() &lt;&lt; &#39;,&#39; &lt;&lt; a1-&gt;g() &lt;&lt; &#39;,&#39; &lt;&lt; a1-&gt;h()
  28. &lt;&lt; &#39;\n&#39;;
  29. }

The output is:

  1. 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.

huangapple
  • 本文由 发表于 2023年4月11日 12:48:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定