gpt4 book ai didi

c++ - 重载函数的调用 - 以继承类作为参数 - 是不明确的

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:23 27 4
gpt4 key购买 nike

这个标题已被多次使用,但在搜索了大约 5-6 个示例后,我找不到与我的问题相匹配的任何内容:

我有一个简单的继承实践。

A 类是基类,BC 类继承自它:

class A {

};

class B : public A { public: int i; };

class C : public A { public: int j; };

还有一个类 P 包含这样的重载函数:

class P
{
public:
void change(B *b)
{
b->i =1;
}

void change(C *c)
{
c->j =1;
}
};

当我使用如下函数时:

int main()
{
A *b = new B();
A *c = new C();
P p;
p.change(b);
p.change(c);
return 0;
}

它给出一个错误提示:

inherit2.cpp: In function ‘int main()’:
inherit2.cpp:37:12: error: call of overloaded ‘change(A*&)’ is ambiguous
inherit2.cpp:37:12: note: candidates are:
inherit2.cpp:21:7: note: void P::change(B*) <near match>
inherit2.cpp:21:7: note: no known conversion for argument 1 from ‘A*’ to ‘B*’
inherit2.cpp:26:7: note: void P::change(C*) <near match>
inherit2.cpp:26:7: note: no known conversion for argument 1 from ‘A*’ to ‘C*’
inherit2.cpp:38:12: error: call of overloaded ‘change(A*&)’ is ambiguous
inherit2.cpp:38:12: note: candidates are:
inherit2.cpp:21:7: note: void P::change(B*) <near match>
inherit2.cpp:21:7: note: no known conversion for argument 1 from ‘A*’ to ‘B*’
inherit2.cpp:26:7: note: void P::change(C*) <near match>
inherit2.cpp:26:7: note: no known conversion for argument 1 from ‘A*’ to ‘C*’

如果你能帮我解决这个问题,我将不胜感激。拉赫曼

最佳答案

Polymorphism is one answer

class A
{
public:
virtual void set() = 0;
};


class B : public A
{
public:
virtual void set() { i = 1; }
private:
int i;
};

class C : public A
{
public:
virtual void set() { j = 1; }
private:
int j;
};

class P
{
public:
void change(A *a)
{
a->set();
}
};

int main()
{
A *b = new B();
A *c = new C();
P p;
p.change(b);
p.change(c);
return 0;
}

有了多态性,就不需要多个change方法。

关于c++ - 重载函数的调用 - 以继承类作为参数 - 是不明确的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12857297/

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