3

基本クラス 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' のメンバーではありません。

どうしたの?

皆さんありがとう!ジョナス

4

1 に答える 1

4

friendこれは のメンバー関数ではVectなく、 の宣言されたフリー関数ですVect(クラス内で定義されているため、メンバー関数のように見えても、ここでは関係ありません。詳細については、FAQを参照してください)。あなたが必要

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

operator*そうは言っても、引数を変更すると、通常、呼び出し元が非常に驚かれるため、非 const 参照を取るのは奇妙です。また、const 値を返す理由がないため、署名を次のように変更することをお勧めします。

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

(同様にVect::operator*)

于 2013-11-02T16:26:08.257 に答える