C ++为派生类调用正确的方法

时间:2019-05-27 15:39:55

标签: c++ inheritance overloading operator-keyword

我希望借助运算符重载在我的代码中拥有一些不错的线性代数。例如。具有向量和标量的乘积看起来像vec *标量,并返回向量。问题是,我有2D和3D向量,并且在编译时不知道它将是哪一个。

我的尝试是一个空的基类以及2D和3D的派生类。但是,由于未调用正确的方法,因此似乎无法正常工作。

#include <cstdlib>
#include <iostream>

class baseVector {
public:
    baseVector() {}
    ~baseVector() {}
    virtual void print() {
        std::cout << "This is not the vector you are looking for" << std::endl;
    }
    virtual baseVector operator*(const double r) const {}
};

class Vector2 : public baseVector {
public:
    Vector2() {}
    Vector2(double x, double y) {
        data_[0] = x;
        data_[1] = y;
    }

    ~Vector2() {}

    void print() {
        std::cout << data_[0] << ", " << data_[1] << std::endl;
    }

    /** Product: Vector * Scalar */
    baseVector operator*(const double r) const {
        Vector2 result(data_[0]*r,
                       data_[1]*r);
        return result;
    }

private:
    double data_[2];
};


int main(int argc, char** argv) {
    // Construct vector of derived type which is not known at compile time
    baseVector * myVec = new Vector2(1, 2);
    const double val = 5;

    baseVector & tempVec = *myVec;
    tempVec.print();

    // Some nice linear algebra here, can't use datatype Vector 2 because it is know known at compile time
    baseVector resVec = tempVec * val;

    // This should print 5, 10
    resVec.print();
    return 0;
}

我希望resVec是类型为Vector2的向量,其值为5、10。相反,它将调用基类的print函数。我知道为什么会这样,但是我如何实现我想要的?

无论如何,这甚至是正确的方法吗?预先感谢您的每一个提示。

编辑:切片不是答案,但解释了为什么它不起作用。我已经找到了可能的解决方案与auto关键字。跳过继承并在主要类型中使用auto而不是特定类型。谢谢大家让我思考。

1 个答案:

答案 0 :(得分:0)

回顾为什么不调用Vector2::print的原因:resVec不是Vector2的实例。具体的,即resVec的最派生类型是baseVector

一个解决方案是放弃对抽象接口的尝试,而只在派生类中提供功能。您可能需要将其实现为非成员函数,以便支持val * tempVec

class Vector2 {
    // ...
    friend Vector2
    operator*(const Vector2& v, double r) {
        return {
            v.data_[0]*r,
            v.data_[1]*r,
        };
    }
    friend Vector2
    operator*(double r, const Vector2& v) {
        return {
            v.data_[0]*r,
            v.data_[1]*r,
        };
    }
};

修改功能virtual baseVector& baseVector::operator*=(double r)是另一种可能的方法。

相关问题