目的是实现一个基类:vector_base ...
对于如何为下面概述的两个向量类创建基类,我有一些误解。
第一:基类是否应为每个派生类都具有一个构造函数,并具有一个默认构造函数?还是有一种方法可以调用基本构造函数来完成这种情况下的派生……
class three: public two
{
private:
double z;
public:
three(double x = 0, double y = 0, double z = 0)
: two(x, y), // call two(double, double) to initialize x & y
z(z)
// ...
};
秒:基类是否应具有两组坐标(x,y,z)静态与动态(指针类型)?
第三:在每种情况下访问器和更改器如何工作;是否有任何理由考虑使用关键字:虚拟关键字和替代关键字?基本上,我不理解如果数据成员为double类型和double *类型,如何实现多态性
class vector_static
{
private:
double x;
double y;
double z;
public:
vector_static(double x = 0, double y = 0, double z = 0)
: x(x), y(y), z(z) {}
vector_static(const vector_static& copy)
: x(copy.x), y(copy.y), z(copy.z) {}
~vector_static()
{
std::cout << "vector_static::~vector_static() " << std::endl;
};
class vector_dynamic
{
private:
double* x = nullptr;
double* y = nullptr;
double* z = nullptr;
public:
vector_dynamic(double x = 0, double y = 0, double z = 0)
: x {new double (x)},
y {new double (y)},
z {new double (z)}
{
}
vector_dynamic(const vector_dynamic& copy)
: x{new double (copy.get_x() )},
y{new double (copy.get_y() )},
z{new double (copy.get_z() )}
{
}
~vector_dynamic()
{
std::cout << "\nvector_dynamic::~vector_dynamic()" << std::endl;
delete x;
delete y;
delete z;
}
};
答案 0 :(得分:1)
vector_static
和vector_dynamic
无关,您不能多态使用它们。他们将需要具有一个通用的基类,该基类定义可以调用以访问坐标的虚函数。然后,您将覆盖每个派生类中的那些方法,以获取或设置坐标;一个将直接访问成员,另一个将取消引用指针。
class vector_generic {
public:
virtual double getX();
virtual void setX(double);
...
}
class vector_static : public vector_generic {
public:
double getX() {
return x;
}
double setX(double newX) {
x = newX;
}
...
}
class vector_dynamic : public vector_generic {
public:
double getX() {
return *x;
}
double setX(double newX) {
*x = newX;
}
...
}
您可以这样做:
vector_generic *vec1 = new vector_static();
vector_generic *vec2 = new vector_dynamic();
cout << vec1->getX() << vec2->getX() << '\n';