C++ 为什么在重载c++;
下面是点和向量的一些类声明C++ 为什么在重载c++;,c++,class,inheritance,operator-overloading,C++,Class,Inheritance,Operator Overloading,下面是点和向量的一些类声明 #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(
#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值设置为另一个值)
由于某些原因,我得到以下错误:
error: ‘float Point::x’ is private within this context
即使此函数在私有上下文中。
有人能解释一下为什么我不能这样做吗?我还有其他函数是成员函数,它们没有这个问题。只有在重载运算符时才会发生这种情况。如果要启用派生以访问基类的私有成员,可以使它们受到
保护
更新:但是要注意,当使用Vec对点
进行子类化时,您使用的是私有继承。如果您真的想使用Point的公共函数作为接口,那么应该使用公共继承。否则,只有Vec类才能使用点函数
#ifndef VECTOR_H
#define VECTOR_H
class Point {
protected:
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);
};
// Maybe you should use public inheritance here
class Vec : /*public*/ 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
中的任何功能都无法访问它。你的意思是让那些成员受到保护吗?这就是私有的意思。。。如果您希望衍生工具能够访问“私有”基类成员,请使用protected
。但实际上并不需要,因为Point
具有公共getter和setter函数。你应该改用这些。我认为这里有一个更大的问题。。。。为什么Vec
源自点
?Vec
是一种点吗?我不这么认为。您可能希望Vec
具有点
。。。甚至多个点。。。请重新考虑您的设计。AVec
是-A点
?这就像说汽车是轮子一样。@JHBonarius好吧,那可能是个例外。汽车是一个火花塞怎么样?那么get_x()
和set_x()
的意义是什么呢?也许这是设计用来作为基类和派生类通用的接口的。@Vasilij Spot on。干杯,伙计。@JHBonarius,我明白了,谢谢!更新了答案,提到了私有继承。注意到了,但是第一次没有注意到。禁止使用基类函数作为接口。他对此很满意,但他正在编写的代码可能会很糟糕;)
#ifndef VECTOR_H
#define VECTOR_H
class Point {
protected:
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);
};
// Maybe you should use public inheritance here
class Vec : /*public*/ 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