如何从派生类中的基类调用运算符?

时间:2013-11-02 16:22:51

标签: c++ operator-overloading

如何从其基类Vect的派生类nVect调用operator *?

class Vect
{

protected:
    int v1_;
    int v2_;
    int v3_;

public:
    Vect( int v1, int v2, int v3 );
    Vect( const Vect &v);
    ~Vect();
    friend const Vect operator*(Vect& v, int n);
    friend const Vect operator*(int n, Vect& v);
};


class nVect : public Vect 
{
//private 
    int pos_;
    int value_;

    void update();

public:
    nVect(int v1, int v2, int v3, int pos, int value);
    nVect(const Vect & v, int pos, int value);
    ~nVect();

    friend const nVect operator*(nVect& v, int n);
    friend const nVect operator*(int n, nVect& v);
};

现在,编译器在以下代码行中抱怨:

const nVect operator*(nVect& v, int n)
{
    return nVect(Vect::operator*(v, n), v.pos_, v.value_);
}

错误:'operator *'不是'Vect'的成员。

出了什么问题?

谢谢大家! 纳斯

1 个答案:

答案 0 :(得分:4)

这是一个自由函数,声明为friend的{​​{1}},而不是Vect的成员函数(即使它看起来像成员函数一样在类中定义,但这不重要,请参阅FAQ以获取更多信息。你需要

Vect

也就是说,为const nVect operator*(nVect& v, int n) { return nVect(static_cast<Vect&>(v)*n, v.pos_, v.value_); } 采用非const引用是很奇怪的,因为如果修改参数,调用者通常会非常惊讶。此外,没有理由返回const值,因此我建议您将签名更改为:

operator*

(同样适用于nVect operator*(const nVect& v, int n) { return nVect(static_cast<const Vect&>(v)*n, v.pos_, v.value_); }

相关问题