开发者

c++ generic pointer? void pointer?

I am writing a program that can take in either 3 ints, or 3 floats in the constructor(I suppose I will need 2 constructors for this). I want to declare an array and store the values in the array "numbers".

If I don't know which constructor will be called I am not sure how to declare "numbers"(as an int array or as a float array)开发者_如何学编程.

Is there a good technique to get around this? or can I create an int array and a float array and somehow have a generic pointer to the array being used(is using a void pointer the best way to do this)?


Looks like you want a templated class.

template <class T>
class Foo
{
public:
    Foo(T a, T b, T c)
    {
        numbers[0] = a;
        numbers[1] = b;
        numbers[2] = c;
    }
private:
    T numbers[3];
};


Can't you use templates for that?

example:

template <class T> 
class Foo {
    public Foo(T a, T b, T c);
};
//
Foo<float> aaa(1.0f, 1.0f, 0.5f);
Foo<int> bbb(1, 2, 3);


Why not to make

class Foo {
public:
    Foo(double a, double b, double c)
        :_a(a), _b(b), _c(c)
    {}

    virtual double get_a() {return _a;}
    virtual double get_b() {return _b;}
    virtual double get_c() {return _c;}
    // more methods

protected:
    double _a, _b, _c;
};

works well for both ints and floats:

Foo ifoo(1, 3, 5);
Foo ffoo(2.0, 4.0, 6.0);

and for mixing them:

Foo mfoo(1, 4.0, 5);

douable storage space is more than enouh for both int and float

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜