我不明白这一点 [英] I dont understand this
问题描述
您好我不明白这一点:
i有一个变量:
PULONG尝试;
为什么在我学习的代码中,我发现了这样的东西? :
试试[2]
i不明白因为PULONG不是和阵列。
谢谢
Hi i dont understand this :
i have one variable :
PULONG try;
why in the code that im studing, i found something like this? :
try[2]
i dont understand becuause PULONG isnt and array.
Thanks
推荐答案
为了使用索引器,类不必是一个数组:想一下泛型列表 - 您可以使用类似数组的索引器语法访问单个元素:
A class doesn't have to be an array in order to use indexers: think of a generic List - you can access individual elements using array-like indexer syntax:
List<String^>^ dinosaurs = gcnew List<String^>();
dinosaurs->Add("Tyrannosaurus");
dinosaurs->Add("Amargasaurus");
dinosaurs->Add("Mamenchisaurus");
dinosaurs->Add("Deinonychus");
dinosaurs->Add("Compsognathus");
for each(String^ dinosaur in dinosaurs )
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);
(取自MSDN示例: http://msdn.microsoft.com/en-us/library/6sh2ey19(v = vs.110).ASPX CS-保存-lang = 1& cs-lang = cpp#code-snippet-3 [ ^ ])
因此,如果您的类派生自支持索引器的类,或实现索引器运算符
operator []
然后完全允许索引。
(Taken from MSDN example: http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-3[^])
So if your class is derived from a class that supports indexers, or implements the indexer operator
operator[]
then indexes are perfectly allowed.
假设您使用C
(尝试
是C ++
保留字,你不能用它来命名变量)和PULONG
以这种方式声明
Assuming you are usingC
(try
is aC++
reserved word, you cannot use it to name a variable) andPULONG
is declared this way
typedef unsigned long * PULONG;
那么你可以写一下,例如
Then you may write, for instance
PULONG try = malloc(100*sizeof(unsigned long));
if ( ! try ) { /* handle error */}
try[2] = 5;
//...
free(try);
编译器不会抱怨。
And the compiler won't complain.
在C / C ++语言,表达式x [y]
相当于*(x + y)
,即内容地址(x + y)
。使用此语法的正常(*)方式是x
是一个数组或指针,y
是一个内存偏移量或数组索引。两种解释都是可能的,实际上是可互换的。
(*):一个鲜为人知的后果是你实际可以交换x
和y
在这样的表达式中,不改变含义:y [x]
将被接受编译器,iffx [y]
是一个有效的表达式,两者的含义是相同的!
In the C/C++ language, the expressionx[y]
is equivalent to*(x+y)
, that is, the contents of address(x+y)
. The normal(*) way to use this syntax is thatx
is an array or a pointer, andy
is a memory offset or array index. Either interpretation is possible, and in fact interchangible.
(*): A less known consequence is that you can actually swapx
andy
in such an expression, without changing the meaning:y[x]
will be accepted by the compiler, iffx[y]
is a valid expression, and the meaning of both is the same!
这篇关于我不明白这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!