如何在派生构造函数中多次构造基类

How to construct base class multiple times in derived constructor

本文关键字:基类 派生 构造函数      更新时间:2023-10-16

你好,我在作业上遇到问题,我需要初始化基本构造函数,该构造函数在多边形的派生构造函数中多次指向。

多边形至少有3个点,每个点都有一个坐标值。 任何人都有想法如何在构造函数初始化中多次初始化基构造函数? 继承思路不是我的想法,是赋值题。

这是个问题

多边形 (构造函数(创建一个具有 n 个点顶点的多边形,顶点从存储在数组点中的顶点中获取其值。请注意,不应假定数组点持续存在;调用构造函数后,可以将其删除。

struct PointType
{
float x;
float y;
};
class Point 
{ 
public:  
Point(const PointType& center );
virtual ~Point();  
private:
PointType m_center;
};
class Polygon : public Point
{ 
public:  
Polygon(const PointType* points, int npoints);  
~Polygon();  
const VectorType& operator[](int index) const;  
private:
int m_npoints;
Object::PointType * m_pt;
}; 

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "Object.hpp"
using namespace std;

const float eps = 1e-5f;
bool Near(float x, float y)
{
return abs(x-y) < eps;
}

float frand()
{
return 10.0f*float(rand())/float(RAND_MAX);
}

int main()
{
srand(unsigned(time(0)));
int count = 0,
max_count = 0;
// Polygon tests
int n = 3 + rand()%8;
float *xs = new float[n],
*ys = new float[n];
float x = 0, y = 0;
PointType *Ps = new PointType[n];
for (int i=0; i < n; ++i) {
xs[i] = frand(), ys[i] = frand();
Ps[i] = PointType(xs[i],ys[i]);
x += xs[i], y += ys[i];
}
}
Point::Point(const PointType& center)
: m_center{center}
{
}
// this is wrong, can correct me how to construct it?
Polygon::Polygon(const PointType* points, int npoints, float depth)
:m_npoints{npoints} , m_pt{new Object::PointType[npoints]}, Point    (*m_pt ,depth)
{
for(int i=0; i < m_npoints ; ++i)
{
m_pt[i] = points[i];
}
}
enter code here

这是分配结构,例如 在此处输入图像描述

我拿走了其他对象类实现

您的作业文本没有说明任何有关继承的内容。它基本上描述了构图。从这里开始:

class Polygon
{ 
public:  
// constructor should allocate the array
Polygon(const PointType* points, int npoints);  
~Polygon();  
private:
Point *m_npoints; // or use smart pointer if you're allowed to.
}; 

这是一个技巧问题,实际上是想让我找到多边形的质心点。

所以我需要一个多边形函数的私有计算中心点并返回多边形中心点的结果,然后在初始化时在点构造函数中调用该函数。