c++泛型指针?空指针
c++ generic pointer? void pointer?
我正在编写一个程序,可以在构造函数中接受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 对于int和float
相关文章:
- C++:将值 int(例如:0x00AAFAD8)转换为指针(指针本身也是 0x00AAFAD8 值)
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 小于非空原始指针和空点之间的运算符
- 未分配正在释放的指针 - 指针问题
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 空弱指针enable_shared_from_this
- 指针?指针功能
- 简单的功能大小;了解指针-指针差异
- 当我删除指针指针时会发生什么
- 将向量向量转换为指针指针
- 理解c++中的指针指针以获得函数调用
- 在指针指针中更改价值
- 指针指针,动态内存分配
- 将共享指针的别名构造函数与空共享指针一起使用C++
- 如何在不取消引用指针的情况下返回指针指针值?
- Visual Studio C++ 空字符串指针
- 指针指针:std:vector vs. 数组
- C :指针与指针指针在二进制树中插入节点
- 无法将空函数指针作为模板参数传递
- 空*到指针