如果继承类型受到保护,我可以制作基类的指针以指向派生对象吗?
can I make a pointer of base class to point to a derived object if inheritance type is protected?
如果我有一个从基类继承的派生类(受保护的或私有的继承),我可以制作基类的指针指向派生对象吗?这是我的 C++ 代码:
#include<iostream.h>
#include<conio.h>
class Geoshape
{
protected:
int dim1;
int dim2;
public:
Geoshape()
{dim1=0;dim2=0;}
Geoshape(int x, int y)
{dim1=x ; dim2=y;}
void setDim1(int x)
{dim1=x;}
int getDim1()
{return dim1;}
void setDim2(int y)
{dim2=y;}
int getDim2()
{return dim2;}
int calculateArea()
{return dim1*dim2;}
};
class Circle:protected Geoshape
{
public:
Circle()
{}
Circle(int r):Geoshape(r,r)
{dim1=r;dim2=r;}
void setR(int r)
{dim1=dim2=r;}
int getR()
{return dim1;}
float calculateArea()
{return 22.0/7*dim1*dim2;}
};
class Triangle:public Geoshape
{
public:
Triangle()
{}
Triangle(int x, int y):Geoshape(x,y)
{}
void setH(int h)
{dim2=h;}
int getH()
{return dim2;}
void setB(int b)
{dim1=b;}
int getB()
{return dim1;}
float calculateArea()
{return .5*dim1*dim2;}
};
class Rectangle:public Geoshape
{
public:
Rectangle()
{}
Rectangle(int x, int y):Geoshape(x,y)
{}
void setL(int l)
{dim1=l;}
int getL()
{return dim1;}
void setH(int h)
{dim2=h;}
int getH()
{return dim2;}
};
class Square:protected Rectangle
{
public:
Square()
{}
Square(int l):Rectangle(l,l)
{dim1=l;dim2=l;}
void setL(int l)
{dim1=dim2=l;}
int getL()
{return dim1;}
float calculateArea()
{return dim1*dim1;}
};
void main()
{
clrscr();
cout<<"enter circle raduis: ";
int raduis;
cin>>raduis;
Circle c1(raduis);
cout<< "this is area of Circle: "<<c1.calculateArea();
getch();
cout<<"nnenter base of triangle: ";
int base;
cin>>base;
cout<<"enter height of triangle: ";
int height;
cin>>height;
Triangle t1(base,height);
cout<< "this is area of Triangle: "<<t1.calculateArea();
getch();
cout<<"nnenter length of rectangle: ";
int length;
cin>>length;
cout<<"enter height of rectangle: ";
int height1;
cin>>height1;
Rectangle r1(length,height1);
cout<< "this is area of Rectangle: "<<r1.calculateArea();
getch();
cout<<"nnenter length of square: ";
int len;
cin>>len;
Square s1(len);
cout<< "this is area of Square: "<<s1.calculateArea();
Geoshape *p1;Geoshape *p2;Geoshape *p3;Geoshape *p4;
p2=&t1;
p3=&r1;
getch();
}
我想在主要中添加这两行:
p1=&c1;
p4=&s1;但这会产生错误!
您只能从类内部(从成员函数和静态成员函数)、派生类(仅在公共或受保护继承的情况下)或从友元函数执行此操作(强制转换为"基"类型)。要不受限制地做到这一点,您可以:
- 使用公共继承,
- 提供用户指定的转换运算符,
- 提供一个函数,该函数将返回这样的指针(本质上与上面相同,但不是以"运算符 T()"的形式,而是"T* getBase()"或类似的 sth 形式) - 成员函数,独立友元函数的静态成员函数。
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 如果基类包含双指针成员,则派生类的构造函数
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 如何在工厂方法中返回指向基于基础操作系统的派生类的有效指针
- 指向基类派生类的 std::unique_ptr 的指针
- 当我在 C++ 中将派生类的指针分配给指针时,地址会更改
- 从基指针到派生的强制转换问题
- 派生类是从基类继承 v 指针并仅使用它,还是也有自己的 v 指针?
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- 从基类指针派生派生类的模板类型
- 指向从指针派生类成员函数的指针,指向基类成员函数
- 访问通过指针派生的类
- 如果未使用虚拟函数,则使用基类指针派生类的任何目的
- 从基指针C++派生类的类型
- 无法从指针派生类转换为指针基类(多态性)
- C++ - 传递智能指针派生类