繁体   English   中英

使用`dynamic_cast`来推断在基类上定义并在派生类上实现的成员函数的参数类型是正确的吗?

[英]Is correct to use `dynamic_cast` to infer the type of an argument of a member function defined on the base class and implemented on a derived class?

我刚开始使用C ++。 我正在尝试为矢量操作的子集设计一个类(接口)。 此抽象基类定义为:

//file: vect.hh
#ifndef _vect_hh
#define _vect_hh
class vect
{
  public:
      virtual double norm() const = 0;
      virtual void   add(const double scaleThis, const double scaleOther,
                         const vect& other)  = 0;
      virtual double dot(const vect& other) const = 0;
      virtual vect* clone() const = 0;
      virtual vect* copy(const vect& other) const = 0;
      virtual ~vect()=default;
};
#endif

问题出现在具有const vect& other参数的const vect& other 因为在派生类中我真正想要的是const vectDerived& other作为参数。 为了举例说明这个问题,我使用原始指针对前一个类进行了简单的实现。 因为我还有其他一些问题,我将在这个问题的最后给出评论,我已经插入了该类的完整定义。 但请记住,最重要的功能是dotadd

// file: vectDouble.hh
#ifndef _vectDouble_hh
#define _vectDouble_hh
#include <cmath>
#include <cstring>

#include "vect.hh"

class vectDouble: public vect
{
public:
    explicit vectDouble(const int n): n{n}, elem{new double[n]}
    {
        std::memset(elem,'\0',sizeof(double)*n);
    }
    ~vectDouble() override {delete[] elem;}
    vectDouble(const vectDouble& other): n{other.n}, elem{new double[n]}
    {
        std::memcpy(elem, other.elem, n*sizeof(double));
    }
    vectDouble& operator=(const vectDouble& other)
    {
        if(&other != this){
            delete[] elem; n = other.n;
            elem = new double[n];
            std::memcpy(elem, other.elem, sizeof(double)*n);
        }
        return *this;
    }
    vectDouble(vectDouble&& other): n{0}, elem{nullptr}
    {
        fillClass(other, *this);
    }
    vectDouble &operator=(vectDouble&& other)
    {
        if(&other != this){
            delete[] elem;
            fillClass(other, *this);
            other.elem = nullptr; other.n = 0;
        }
        return *this;
    }
    double norm() const override
    {
        double norm = 0.0;
        for(int i=0;i<n;i++){norm += elem[i]*elem[i];}
        return std::sqrt(norm);
    }
    double dot(const vect& other) const override
    {
        const vectDouble &v = dynamic_cast<const vectDouble&>(other);
        double dot = 0.0;
        for(int i=0;i<n;i++){dot += elem[i]*v.elem[i];}
        return dot;
    }
    void add (const double scaleThis, const double scaleOther,
          const vect& other) override
    {
        const vectDouble &v = dynamic_cast<const vectDouble&>(other);
        for(int i=0;i<n;i++){
                elem[i] = scaleThis*elem[i] + scaleOther*v.elem[i];
        }
    }
    double& operator[](const int i){return elem[i];}
    const double& operator[](const int i) const {return elem[i];}
    int size() const{return n;}
    vectDouble* clone() const override
    {
        return new vectDouble(*this);
    }
    vectDouble* copy(const vect& other) const override
    {
        const vectDouble &v = dynamic_cast<const vectDouble&>(other);
        auto *t = new vectDouble(*this);
        t->n = v.n;
        std::memcpy(t->elem, v.elem, t->n*sizeof(double));
        return t;
    }
private:
    void fillClass(const vectDouble& in, vectDouble& out)
    {
        out.n = in.n; out.elem = in.elem;
    }
    int    n;
    double *elem;
};
#endif

在这两个函数中我使用了const vectDouble &v = dynamic_cast<const vectDouble&>(other); 将基类引用转换为具有派生类类型的引用。 这是dynamic_cast的有效用例。 如果没有,实现这一结果的正确方法是什么?

我已经说过我遇到了其他问题(抱歉偏离了主要问题)。 作为使用抽象类和先前实现的例子,我做了这个简单而有点人为的主程序:

    // file main.cc
#include <iostream>
#include <memory>
#include "vectDouble.hh"

double lsfit(const vect& dobs, const vect& dcalc)
{
    std::unique_ptr<vect> tmp(dcalc.copy(dcalc));

    return (dobs.dot(dcalc))/(dcalc.dot(*tmp));
}

void testFit()
{
    vectDouble d{10};
    vectDouble x{10};

    for(int i=0;i<x.size();i++){
    d[i] = static_cast<double>(3*i);
    x[i] = static_cast<double>(i);
    }
    std::cout<<"alpha="<<lsfit(d, x)<<std::endl;
}

int main()
{
    testFit();
    return 0;
}

该程序说明了为所描述的接口设想的一个用例。 但是,如果不使用std::unique_ptr ,则会发生内存泄漏(使用选项-fsanitize=leak g ++编译器中的泄漏标识)。 如果不是使用unique_ptr我想手动管理内存(作为好奇心),清除此结果的正确方法是什么? 可以直接从复制函数返回std::unique_ptr 当我尝试这样做时,我收到了与错误的协变返回类型相关的错误消息。

备注:1)此接口的目的是抽象用于表示数组的存储方案,例如文件而不是内存表示。 2)我知道所提供的复制功能更类似于创建/克隆加复制功能。 3)如果将来我想在基类和派生类中使用模板,那么所呈现的结构是否足够? 例如template<float> class vect{...}template <float> class vectDerived{...}

根据@hayt的建议,我已经更改了vect.hhvectDouble.hh的定义,以使用所描述的CRTP模式。 在这些更改后,我还将函数lsftit的定义更改为:

template <class Derived> double lsfit2(const Derived& dobs, const Derived& dcalc)
{
    std::unique_ptr<Derived> tmp = dcalc.clone();
    Derived *t = tmp.get();
    t->copy(dcalc);
    return (dobs.dot(dcalc))/(dcalc.dot(*t));
}

这是使用此模式时定义此功能的正确方法吗?

谢谢。

您应该检查是否确实需要继承,并且可能使用模板参数切换到一个通用向量类(从您只有“double”作为特定的东西)

另一种方法是将CRTP与声明接口结合使用。 (我还在这个apporach中添加了unique_ptr)

template <class Derived>
class vect
{
  public:
      virtual double norm() const = 0;
      virtual void   add(const double scaleThis, const double scaleOther,
                         const Derived& other)  = 0;
      virtual double dot(const Derived& other) const = 0;
      virtual std::unique_ptr<Derived> clone() const = 0;
      virtual std::unique_ptr<Derived> copy(const vect& other) const = 0;
      virtual ~vect()=default;
};

这样你就拥有了相同的“接口”,但却有一个不同的“基类”,你的函数中也有派生类。 因此,您不必担心通过接口将“不兼容”向量相互分配(请参阅dynamic_cast)。

此外,您可以稍后派生该类以获得更多规范。

以下是您使用此方法看起来的类:

class vectDouble: public vect<vectDouble>
{
public:
    //...
    //NOTE: here vecDouble is a parameter. no need for dynamic casts
    double dot(const vectDouble& other) const override
    {        
        double dot = 0.0;
        for(int i=0;i<n;i++){dot += elem[i]*other.elem[i];}
        return dot;
    }
    void add (const double scaleThis, const double scaleOther,
          const vectDouble& other) override
    {

        for(int i=0;i<n;i++){
                elem[i] = scaleThis*elem[i] + scaleOther*other.elem[i];
        }
    }
    //also directly a unique pointer
    std::unique_ptr<vectDouble> clone() const override
    {
        return std::make_unique<vectDouble>(*this);
    }
    //...
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM