如何在C ++

时间:2016-12-22 16:02:34

标签: c++ arrays

我有一个类Array,它实现了类型为T的元素的通用二维数组:

#ifndef _ARRAY_
#define _ARRAY_

namespace math
{

template <typename T>
class Array
{
protected:
    //! Flat storage of the elements of the array of type T
    T * buffer;                     

    //! The width of the array (number of columns)
    unsigned int width,             

    //! The height of the array (number of rows)
                 height;            

public:

    /*! Reports the width (columns) of the array
     *
     * \return the width.
     */
    unsigned int getWidth() const { return width; }      

    /*! Reports the height (rows) of the array
     *
     * \return the height.
     */
    unsigned int getHeight() const { return height; }    

    template <typename T>
    T & Array<T>::operator () (int x, int y) {
        float loc = y*width + x;
        return *(buffer + loc);
    }

    template <typename T>
    Array<T>::Array(unsigned int w, unsigned int h):width(w),height(h) {}

    template <typename T>
    Array<T>::Array(const Array<T> & source):width(source.width),height(source.height) {}                   

    template <typename T>
    Array<T>::Array & operator = (const Array<T> & source) {
        width = source.width;
        height = source.height;
        return *this;
    }

    /*! Virtual destructor.
     */
    virtual ~Array();                                    

};

} // namespace math

#endif

我还有一个名为Image的派生类,用于存储ppm图像的图像数据:

using namespace std;
#include <iostream>
#include "Image.h"

namespace math
{

class Image : public Array<Vec3<float>> {
protected:

    Vec3<float> * buffer;

public:


    //Obtains the color of the image at location (x,y).
    Vec3<float> getPixel(unsigned int x, unsigned int y) const {
        if (x > 0 && x < Array::getWidth() && y > 0 && y < Array::getHeight()) {
            float pixel_r = (x, y);
            float pixel_g = (x, y) + 1;
            float pixel_b = (x, y) + 2;
            Vec3<float> c = Vec3<float>(pixel_r, pixel_g, pixel_b);
            return c;
        }
        Vec3<float> c = Vec3<float>();
        return c;
    }

    //Constructor

    Image(int w, int h, Vec3<float> * t_buffer) : Array(w, h), buffer(t_buffer) {}

    //Copy Constructor
    Image(const Image & src) : Array(src) {
        memcpy(buffer, src.buffer, sizeof(Vec3<float>));
    }

    //Copy assignment operator
    Image & operator = (const Image& right) {
        operator=(right);
        if (buffer != nullptr)
            delete[] buffer;
        memcpy(buffer, right.buffer, sizeof(Vec3<float>));
        return *this;
    }

    //The Image destructor.
    ~Image() {
        if (buffer) delete[] buffer;
    }
};
}

我的问题是如何在Image类中使用Array类的getWidth()和getHeight()函数。

0 个答案:

没有答案