何时将类的引用分配给其父类的 instace

When to allocate a reference of a class to an instace of its parent class?

本文关键字:父类 instace 引用 何时 分配      更新时间:2023-10-16

我正在阅读如下代码的和平。

class CPolygon { 
    protected: 
        int width, height; 
    public: 
        void set_values (int a, int b) { width=a; height=b; } 
        virtual int area () { return (0); } 
}; 
class CRectangle: public CPolygon { 
    public: 
        int area () { return (width * height); } 
}; 
class CTriangle: public CPolygon { 
    public: 
        int area () { return (width * height / 2); } 
}; 

在使用此类后,我们有一个代码,在此代码中,CRectangle 类的引用被分配给其父级"CPolygon",如下所示:

main () { 
   CRectangle rect; 
   CTriangle trgl; 
   CPolygon poly; 
   //*****This part is when a reference of the derived class is
   //allocated to an instance of its parent class *****
   CPolygon * ppoly = ▭ 
   .
   .
}

所以我的问题是,当我们这样做时,为什么这个代码行不是这样的:

CPolygon * ppoly = new rect; 

谢谢

示例中的代码创建一个指针,指向已存在的变量 rect 。您可以创建一个指向该类型的新变量的指针,而不是指向已经存在的变量,如下所示

CPolygon* ppoly1 = new CRectangle;

但是,rect 是一个变量,而不是一个类型,因此调用 new rect 是没有意义的。

>CPolygon * ppoly = new rect;是一个无效的构造,因为rectmain()方法中定义的变量,而new运算符需要一个类(或数组,或结构等)。

另一方面,CPolygon * ppoly = ▭赋值将ppoly值设置为 rect 变量的堆栈地址。将指针从子类强制转换为父类是可能的,并且是合法的。

此外,您的问题的标题有点偏离课程,因为您无法分配引用,只能分配指针(甚至不能分配指针,因为它实际上是分配/保留的内存并返回地址)