2016-12-17 39 views
-1

我想定义运算符()(int x,int y)函数,但我无法理解如何定义它。 我在Array.h文件中有此功能,所以我必须在Array.hpp文件中定义它,我认为。有人有任何想法吗?例如,使用模板在运营商中实现

#ifndef _ARRAY_ 
#define _ARRAY_ 

namespace math 
{ 

/*! The Array class implements a generic two-dimensional array of elements of type T. 
*/ 
    template <typename T> 
    class Array 
    { 
    protected: 
    //! Flat storage of the elements of the array of type T 
     T * buffer;      
     unsigned int width,   
        height; 
     /* Returns a reference to the element at the zero-based position (column x, row y). 
     * 
     * \param x is the zero-based column index of the array. 
     * \param y is the zero-based row index of the array. 
     * 
     * \return a reference to the element at position (x,y) 
     */ 
     T & operator() (int x, int y); 

     }; 
    } // namespace math 

#include "Array.hpp" 
#endif 
+0

你问的是如何定义它的行吗?或者如何实现它? – doctorlove

+0

@doctorlove我问如何定义它,谢谢 – madrugadas25845

回答

0

这样的例子。

template <typename T> 
class Array 
{ 
protected: 
    //! Flat storage of the elements of the array of type T 
    T * buffer; 
public:      
    unsigned int width, height; 
    /// non-constant element access 
    /// \param[in] x is the zero-based column index of the array. 
    /// \param[in] y is the zero-based row index of the array. 
    /// \return a reference to the element at position (x,y) 
    T & operator() (int x, int y) 
    { 
    return (buffer+x*height)[y]; 
    } 
    /// constant element access 
    /// \param[in] x is the zero-based column index of the array. 
    /// \param[in] y is the zero-based row index of the array. 
    /// \return a const reference to the element at position (x,y) 
    T const & operator() (int x, int y) const 
    { 
    return const_cast<Array&>(*this)(x,y); // note: re-use the above 
    } 
};