为什么我不能在此代码中将 A* 转换为 B*?

Why can't I convert an A* to a B* in this code?

本文关键字:转换 不能 代码 为什么      更新时间:2023-10-16

我不明白我在做什么错。我收到错误:上面的行:

从a*到b*的无效转换:
   B *p3=new A(p2->operator+(*p1));

这是完整的代码。

#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
class A
{
  protected: int x;
  public: A(int i=-31) {x=i;}
  virtual A operator+(A a) {return x+a.x;}
};
class B:public A
{
  public:B(int i=12) {x=i;}
  B operator+(B b) {return x+b.x+1;}
  void afisare() {cout<<x;}
};
int main()
{
  A *p1=new B, *p2=new A;
  B *p3=new A(p2->operator+(*p1));
  p3->afisare();
  //cout << "Hello world!" << endl;
  return 0;
}

我认为您在这里有继承。如果您具有A*类型的指针,则可以指向类型A的对象或类型B的对象,因为B类型的对象也是类型A的对象。但是,您不能在类型A的对象上具有类型B*点的指针,因为并非所有类型A的对象都属于B类型。

独立,您可以重写该行

B *p3 = new A(p2->operator+(*p1));

AS

B* p3 = new A(p2 + *p1);

这可能会使内容更容易阅读。

多态性仅以一种方式起作用。基本指针可以指向派生的类,因为派生类的所有内容都具有基类所做的一切。但是,派生的指针不能指向基础,因为派生的类有基类没有的东西。

 class A
    {
    }
    class B:public A
    {
    }

upcasting:A *a=new B;(主要是在覆盖时使用)

降低:B *b=(B*)a;仅在您要施放的指针(在我们的情况下a)指向混凝土派生对象时才有效。