何时将类的引用分配给其父类的 instace
When to allocate a reference of a class to an instace of its parent class?
我正在阅读如下代码的和平。
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;
是一个无效的构造,因为rect
是main()
方法中定义的变量,而new
运算符需要一个类(或数组,或结构等)。
另一方面,CPolygon * ppoly = ▭
赋值将ppoly
值设置为 rect
变量的堆栈地址。将指针从子类强制转换为父类是可能的,并且是合法的。
此外,您的问题的标题有点偏离课程,因为您无法分配引用,只能分配指针(甚至不能分配指针,因为它实际上是分配/保留的内存并返回地址)
相关文章:
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 在运行时选择父类的实现
- 如何在C++子类中访问父类的私有变量
- 将父类的子类的数据复制到具有相同父类的另一个类
- 父类的私有函数会导致对具有相同名称和相似参数的子类中的公共函数的不明确调用
- C++ 将子类的对象添加到父类的向量中
- 两个父类的构造函数的序列
- 为什么我的子类不继承父类的字符串?
- C++调用使用重写函数的父类函数
- 在父类中公开受保护的构造函数
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 如何使父类不重复已经执行的祖父方法
- 从模板化父类中的派生内部类访问受保护的成员变量
- Arduino在子类中使用父类方法
- 使用 Clang LibTooling 扫描C++在模板化父类中调用本地类的源
- 从父类的向量访问子类函数,而无需向下转换
- 将派生类的构造函数声明为父类的友元