【问题标题】:Understanding base to derived class casting and conversion errors了解基类到派生类的转换和转换错误
【发布时间】:2021-05-21 08:03:31
【问题描述】:

(以下是简化解释的示例,但它很好地反映了我的实际问题)

我有这些类和函数,我无法更改或修改:

CannotChangeThis.h

class baseRectangle
{
  public:
    baseRectangle() : x(0),y(0),w(0),h(0) {}
    baseRectangle(int xx, int yy, int ww, int hh) : x(xx),y(yy),w(ww),h(hh) {}

    int x,y,w,h; // left, top, width, height
    void SetRectangle(int xx, int yy, int ww, int hh)
    {
      x=xx;y=yy;w=ww;h=hh;
    }
    int GetRight() {return w-x-1;}
    int GetBottom() {return h-y-1;}
    
    [other methods]
}
baseRectangle GetABaseRectangle();
void PassABaseRectangle(baseRectangle br);

当您更改基类数据时,我有一个派生类进行一些计算:

MyNewClass.h

class DerivedRect : public BaseRectangle
{
  private:
    DoPreComputation()
    {
      r=w-x-1;b=h-y-1;
      cx=ww/2;cy=hh/2;
    }
  public:

    int r,b,cx,cy;  // right, bottom, centerX, centerY
    DerivedRect () : r(0),b(0),cx(0),cy(0) {}

    void SetRectangle(int xx,yy,ww,hh)
    {
      BaseRectangle::SetRectangle(int xx,yy,ww,hh);
      DoPreComputation();
    }
    int GetRight() {return r;}
    int GetBottom() {return b;}
    
    DerivedRect &operator=(const BaseRectangle &r1 )
    {
        if (&r1 == this) { return *this; } // prevent assigning to self
        BaseRectangle ::operator=(r1);
        DoPreComputation();
        return *this;
    }
}
DerivedRect GetADerivedRect();
void PassADerivedRect(DerivedRect dr);

我的问题:

AdvRect rr;
rr = hRect; // this works

AdvRect ar = hRect; // this cause error "conversion from 'BaseRectangle ' to non-scalar type 'DerivedRect' requested"
PassADerivedRect( GetABaseRectangle() );  // Error "no known conversion for.."
PassABaseRectangle( GetADerivedRect() );  // Error "no known conversion for.."

我认为我缺少一些关于在基类和派生类之间转换或转换的基本知识。

我在 stackoverflow 中看到了对象切片是什么,但是由于我的派生类只是对相同的数据进行“预计算”,我认为这应该不是问题。

我做错了什么?

【问题讨论】:

    标签: class c++11 inheritance


    【解决方案1】:

    不是转换赋值运算符,而是转换构造函数。

    class DerivedRect : public baseRectangle {
      public:
        DerivedRect(const baseRectangle &r1 ) : baseRectangle(r1) {
            DoPreComputation();
        }
    
        // DerivedRect &operator=(const BaseRectangle &r1 ) // no need for this
    
        int r = 0, b = 0, cx = 0, cy = 0;  // right, bottom, centerX, centerY  
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-08
      • 2013-11-17
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多