C++ 父类的指针数组,具有纯虚函数和指针数组的对象类型
在main函数中,我想创建一个指针数组。对象类型应该每次都更改。 像这样的。 形状*a[10]=新矩形; 但我想制作一个[0]矩形类型。a[1]圆形类型等C++ 父类的指针数组,具有纯虚函数和指针数组的对象类型,c++,arrays,pointers,inheritance,virtual-functions,C++,Arrays,Pointers,Inheritance,Virtual Functions,在main函数中,我想创建一个指针数组。对象类型应该每次都更改。 像这样的。 形状*a[10]=新矩形; 但我想制作一个[0]矩形类型。a[1]圆形类型等 class shape { public: virtual float boundary_length()=0; }; class rectangle: public shape { public: float boundary_length() { co
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;
}
类形状
{
公众:
虚拟浮点边界_length()=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