gpt4 book ai didi

c++ - 多态性c++错误输出

转载 作者:行者123 更新时间:2023-11-28 02:03:58 25 4
gpt4 key购买 nike

<分区>

为什么此代码的输出是 A 类,我希望看到“AAA 类”

#include <iostream>    
using namespace std;

class A
{
public:
A(){}
virtual int Method1(int a, int b){cout << "Class A" << endl; return a+b; }
};

class AA:public A
{
public:
AA(){}
int Method1(int a, int b){cout << "Class AA" << endl; return a*b;}
};

class AAA:public A
{
public:
AAA(){}
int Method1(int a, int b){cout << "Class AAA" << endl; return a/b;}
};

class B
{
public:
B(){}
B(A a):obj(&a){}
int Method2(int a, int b){ return obj->Method1(a,b);}

private:
A *obj;
};

int main() {
A *a = new AAA();
B *b = new B(*a);
b->Method2(2,1);
return 0;
}

我将新的 AAA 对象传递给 B 类并分配给 *obj。这有什么问题?最好的问候,

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