【问题标题】:Why can't I convert an A* to a B* in this code?为什么我不能在此代码中将 A* 转换为 B*?
【发布时间】:2017-09-17 20:08:27
【问题描述】:

我无法理解我做错了什么。我收到错误:上述行从 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 不是B 那么您期待什么?您不能将 A 分配给 B 类型的指针。
  • 好的,我明白你在说什么,但你如何纠正它?
  • 改为创建B
  • int main() { A *p1=new B, *p2=new B; B *p3=new B(p2->运算符+(*p1)); p3->afisare(); //cout

标签: c++ pointers inheritance


【解决方案1】:

我认为你的继承权倒退了。如果您有一个A* 类型的指针,它可以指向A 类型的对象或B 类型的对象,因为B 类型的对象也是A 类型的对象.但是,您不能让B* 类型的指针指向A 类型的对象,因为并非所有A 类型的对象也是B 类型。

可以独立改写一行

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

作为

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

这可能会使事情更容易阅读。

【讨论】:

    【解决方案2】:

    多态性只有一种方式。基指针可以指向派生类,因为派生类具有基类所做的一切。然而,派生指针不能指向基类,因为派生类具有基类没有的东西。

    【讨论】:

      【解决方案3】:
       class A
          {
          }
      
          class B:public A
          {
          }
      

      向上转换:A *a=new B;(主要用于覆盖)

      向下转换:B *b=(B*)a; 它仅在您尝试转换的指针(在我们的例子中为 a)指向具体派生对象时才有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-05
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-14
        • 1970-01-01
        相关资源
        最近更新 更多