Jam*_*mes 0 c++ arrays visual-studio visual-c++
我正在编写一个程序,可以在构造函数中使用3个int或3个浮点数(我想我需要2个构造函数).我想声明一个数组并将值存储在数组"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];
};
Run Code Online (Sandbox Code Playgroud)
你不能使用模板吗?
例:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
448 次 |
| 最近记录: |