【发布时间】:2021-01-09 20:56:48
【问题描述】:
以下是点和向量的一些类声明
#ifndef VECTOR_H
#define VECTOR_H
class Point {
private:
float x;
float y;
public:
Point();
Point(float x, float y);
float get_x() const;
float get_y() const;
void set_x(float x);
void set_y(float y);
};
class Vec : Point {
public:
Vec(float x, float y, float x1, float y1);
Vec cross(Vec &v);
Vec cross(float value);
Vec dot(Vec& v);
Vec mag();
Vec normalize();
Vec rotate(float w);
Vec operator+(const Vec& v);
Vec operator-(const Vec& v);
Vec operator*(float s);
Vec operator/(float s);
};
#endif
这是我实现的运算符重载函数之一(现在我只是调用将 x 值设置为另一个值)
Vec Vec::operator+(const Vec& v) {
this->x = 0;
}
由于某种原因,我收到以下错误:
error: ‘float Point::x’ is private within this context
即使这个函数在私有上下文中。 有人可以解释为什么我不能这样做吗?我有其他函数是成员函数,它们没有这个问题。只有当我重载运算符时才会发生这种情况。
【问题讨论】:
-
x是Point的私有成员,而不是Vec。Vec中没有任何功能可以访问它。你的意思是让那些成员protected? -
这就是
private的意思...如果您希望派生类可以访问“私有”基类成员,请使用protected。但这实际上是不需要的,因为Point具有公共 getter 和 setter 函数。你应该改用这些。 -
我认为这里有一个更大的问题......为什么
Vec是从Point派生而来的?Vec是Point的一种吗?我不这么认为。您可能希望Vec拥有Point...甚至多个点...请重新考虑您的设计。 -
A
Vec是-aPoint?这就像说汽车就是轮子。 -
@JHBonarius 好吧,这可能是个例外。 Car is-a Sparkplug 怎么样?
标签: c++ class inheritance operator-overloading