当前位置: 动力学知识库 > 问答 > 编程问答 >

Pointers to elements of a C++ class

问题描述:

I have a C++ class c_image which contains a vector of pointers to elements of class c_pixel:

class c_image {

public:

vector<shared_ptr<c_pixel>> pixel;

...

};

Class c_pixel elements contain an element Z of type double:

class c_pixel {

public:

double Z;

...

};

However, they are extended with class c_pixel_pv, which contains pv, an array of three elements of type double:

class c_pixel_pv : public c_pixel {

public:

double pv[3];

...

};

Class c_image also has a function filter

vector<double> c_image::filter(???) {

...

};

which will take as input a pointer to the elements Z or pv[0] or pv[1] or pv[2].

But I have no idea how to point to these elements. I don't even know if it is possible to point, for example, only to pv[0] elements. I have no clue how to begin with this problem. Can anybody help me?

网友答案:

You could (and probably should) use polymorphism and have a virtual member function in the c_pixel class that is overridden in the c_pixel_pv class. This member function performs whatever operation is needed using the correct member variables, and is called from c_image::filter.

网友答案:

The OOP concept - polymorphism would come in handy now. A virtual member function (A virtual member is a member function that can be redefined in a derived class, while preserving its calling properties, through references) in the c_pixel class, overridden in the derived c_pixel_pv class, could perform the operation you need with the correct variables.

You will need to call this member function from the vector<double> c_image::filter().

网友答案:

You could use a function rather than a pointer:

using Selector = std::function<double(const c_pixel&)>;

vector<double> c_image::filter(Selector select) {
    // Trivial example that just copies
    vector<double> result;
    result.reserve(pixel.size());
    for (auto pix: pixel)
    {
        result.push_back(select(*pix)); 
    }
    return result;
};

double z(const c_pixel& p)
{
    return p.Z;
}

c_image image;
// ...
vector<double> = image.filter(z);

But you'd need some way to discriminate between the different types of pixel, like a tag byte or a virtual function (so they would take up even more room and you already have a lot of overhead).

If you don't need to mix pixel types in an image, you could use a template class, templated on the pixel type.
Then you could get rid of the runtime pixel discrimination.
(To be honest, it's difficult to picture how a function like filter would handle pixels of a type that doesn't have the element it's supposed to use.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: