具有纯虚函数和指针数组对象类型的父类的指针数组

pointer array of parent class having a pure virtual function and object type of pointer array

本文关键字:数组 指针 父类 对象 类型 函数      更新时间:2023-10-16

在主函数中,我想创建一个指针数组。 对象类型每次都应该更改。 像这样的东西。 形状* a[10]=新矩形; 但我想做一个[0]矩形类型。a[1] 圆形等。

class shape
{
public:
virtual float boundary_length()=0;
};
class rectangle: public shape
{
public:
float boundary_length()
{
cout<<"Boundary length of rectangle"<<endl;
return 2*(length+width);
}
};
class circle: public shape
{
public:
float boundary_length()
{
return 2*(3.14*radius);
}   
};
class triangle: public shape
{
float boundary_length()
{
return (base+perp+hyp);
}
};
int main()
{
shape* a=new rectangle;
return 0;
}

如果我理解正确,您需要以下内容

#include <iostream>
class shape
{
public:
virtual float boundary_length() const = 0;
virtual ~shape() = default;
};
class rectangle: public shape
{
public:
rectangle( float length, float width ) : length( length ), width( width )
{
}
float boundary_length() const override
{
return 2*(length+width);
}
protected:
float length, width;
};
class circle: public shape
{
public:
circle( float radius ) : radius( radius )
{
}
float boundary_length() const override
{
return 2*(3.14*radius);
}
private:
float radius;
};
//...
int main(void) 
{
const size_t N = 10;    
shape * a[N] =
{
new rectangle( 10.0f, 10.0f ), new circle( 5.0f )
};
for ( auto s = a; *s != nullptr; ++s )
{
std::cout << ( *s )->boundary_length() << 'n';
}        
for ( auto s = a; *s != nullptr; ++s )
{
delete *s;
}        
}

程序输出为

40
31.4