【问题标题】:Why can I not access private members when overloading c++ [closed]为什么重载c ++时无法访问私有成员[关闭]
【发布时间】: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

即使这个函数在私有上下文中。 有人可以解释为什么我不能这样做吗?我有其他函数是成员函数,它们没有这个问题。只有当我重载运算符时才会发生这种情况。

【问题讨论】:

  • xPoint 的私有成员,而不是 VecVec 中没有任何功能可以访问它。你的意思是让那些成员protected
  • 这就是private 的意思...如果您希望派生类可以访问“私有”基类成员,请使用protected。但这实际上是不需要的,因为Point 具有公共 getter 和 setter 函数。你应该改用这些。
  • 我认为这里有一个更大的问题......为什么Vec 是从Point 派生而来的? VecPoint 的一种吗?我不这么认为。您可能希望Vec 拥有 Point...甚至多个点...请重新考虑您的设计。
  • A Vec 是-a Point?这就像说汽车就是轮子。
  • @JHBonarius 好吧,这可能是个例外。 Car is-a Sparkplug 怎么样?

标签: c++ class inheritance operator-overloading


【解决方案1】:

如果您想让派生类能够访问基类的私有成员,您可以将它们设为protected

更新:但请注意,当使用 Vec 子类化 Point 时,您使用的是私有继承。如果你真的想使用Point的公共函数作为接口,你应该使用公共继承。否则只有 Vec 类才能使用 Point 函数。

#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

【讨论】:

  • 那么get_x()set_x()有什么意义呢?
  • 也许它被设计为一个接口,应该是基类和派生类通用的接口。
  • @Vasilij 现场。干杯伙伴。
  • @JHBonarius,点了,谢谢!更新了答案,提到了私有继承。注意到它,但第一次没有注意它。禁止使用基类函数作为接口。
  • 他对此很满意,但他编写的代码可能很糟糕;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 2014-12-12
  • 2014-08-05
  • 2012-09-24
相关资源
最近更新 更多