c++泛型指针?空指针

c++ generic pointer? void pointer?

本文关键字:空指针 指针 泛型 c++      更新时间:2023-10-16

我正在编写一个程序,可以在构造函数中接受3个整型或3个浮点数(我想我需要2个构造函数)。我想声明一个数组,并将值存储在数组"numbers"中。

如果我不知道将调用哪个构造函数,我不确定如何声明"numbers"(作为int数组或float数组)。

是否有一个好的技术来绕过这个?或者我可以创建一个int数组和浮点数组,并以某种方式有一个通用的指针指向正在使用的数组(使用一个void指针是最好的方法来做到这一点)?

看起来你想要一个模板化的类。

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];
};

不能使用模板吗?

的例子:

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);

为什么不让

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;
};

对int型和浮点型都有效:

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

和用于混合它们:

Foo mfoo(1, 4.0, 5);

double 对于intfloat

来说,存储空间是足够的。