创建一个位字段的 UserArray,可以声明如下:我们的数组占用的大小将小于普通数组。假设我们想要一个包含 20 个标志 (TRUE/FALSE) 的数组。 bool FLAG[20]
将占用 20 个字节的内存,而 UserArray<bool,bool,0,20>
将占用 4 个字节的内存。
- 使用类模板创建用户数组。
- 使用位运算符来打包数组。
平等经营也要落实。
template<class T,int W,int L,int H>//i have used template<class T> //but never used such way class UserArray{ //.... }; typedef UserArray<bool,4,0,20> MyType;
哪里:
- T = 数组元素的类型
- W = 数组元素的宽度,0 < W < 8
- L = 数组索引的下限(最好为零)
- H = 数组索引的上限
主程序:
int main() {
MyType Display; //typedef UserArray<T,W,L,H> MyType; defined above
Display[0] = FALSE; //need to understand that how can we write this?
Display[1] = TRUE; //need to understand that how can we write this?
//assert(Display[0]);//commented once, need to understand above code first
//assert(Display[1]);//commented once..
//cout << “Size of the Display” << sizeof(Display);//commented once..
}
我的疑问是这些参数如何,即 T,L,W & H
在类里面使用 UserArray
以及我们如何编写 UserArray
的实例作为Display[0]
& Display[1]
它代表什么?
类似类型的简短示例对我来说很容易理解。
最佳答案
W
, L
和 H
是非类型模板参数。您可以使用常量值实例化模板(在编译时),例如:
template <int N>
class MyArray
{
public:
float data[N];
void print() { std::cout << "MyArray of size " << N << std::endl; }
};
MyArray<7> foo;
MyArray<8> bar;
foo.print(); // "MyArray of size 7"
bar.print(); // "MyArray of size 8"
在上面的例子中,到处都是N
出现在模板定义中,它将在编译时被提供的常量替换。
请注意 MyArray<7>
和 MyArray<8>
就编译而言,它们是完全不同的类型。
我不知道您的具体问题的解决方案是什么。但是您的代码目前无法编译,因为您没有为模板参数提供值。
关于c++ - 了解用户自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6691560/