I have a base class with many child classes. How would I implement a template operator over loader in the base class to work for all the inheriting classes? I tried to make one with the + operator but it complained that I had too many parameters. I'm not actually sure this is the right way to go about doing this (I'm just starting to use OOP) so if you can think of a better way that would also be great.

I'm making a library in which each metric space is a class. I want to make a base class "Operations" that every space inherits.

My template base class:

#ifndef __libSpace__Operations__
#define __libSpace__Operations__

template< typename T >
class Operations{
public:
    friend T operator+( const T& sp, const T& nsp ){
        return T(sp.dimension + nsp.dimension);
    };
};

#endif

child:

#ifndef __libSpace__EuclidSP__
#define __libSpace__EuclidSP__

#include "Operations.h"

class EuclidSP: public Operations<EuclidSP>{
public:
    EuclidSP(int n = 0, ...);
    ~EuclidSP();

    double* vector();

private:
    int dimension;
    double *vec = new double(dimension);
};

#endif

main:

#include <iostream>
#include "EuclidSP.h"

int main(int argc, const char * argv[])
{
EuclidSP ob1(3,4.0,5.0,6.0);
EuclidSP ob2(3,2.0,5.0,3.0);
EuclidSP obj3();

obj3 = ob2+ob1;

return 0;
}
有帮助吗?

解决方案

A member operator +() have only one parameter, the right operand. The left or first is always *this. Depending of your situation, you need just a base +, a virtual + or a template. A free operator +() take two argumets, "left" and "right".

In your code:

template< typename T >
class Operations{
public:
    friend T operator+( const T& sp, const T& nsp ){
        return T(sp.dimension + nsp.dimension);
    };
};

You whant a member or a friend?

If a friend, the problems is that +() have to be define outside the class, it is only a friend, not a member.

template< typename T >
    T operator+( const T& sp, const T& nsp );

template< typename T >
class Operations{
public:
    friend T operator+<T>( const T& sp, const T& nsp );

};

template< typename T >
    T operator+( const T& sp, const T& nsp )
    {
        return T(sp.dimension + nsp.dimension);
    }

BUT !!!! Now you have the REAL problem: +() uses a privat member of the derived class, not the base class, so it need to be a friend of the derived class. I think you need to rethink ;-) your design. If you are so confortable using dimension in Operations.. could it be a protected member of Operations??? All your Operations have an dimension?

其他提示

Your base class should know the derived types class by receiving it as a template parameter and implement operator+ as friend:

template< typename T >
class base
{
    friend T operator+( const T& lhs, const T& rhs )
    {
       // your generic implementation here...
    }
};

the derived classes then derive from the base class like this:

class D1 : public base<D1> { ... };
class D2 : public base<D2> { ... };
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top