我尝试过搜索回复,但不幸的是,示例似乎太复杂了,我无法理解。最根本的是,我想知道如何传递和更改指针数组的地址。
例子:
class Foo {
M** arryM;
...
arryM = new M*[10];
...
void Foo::replace(int ind, M &newm) {
// Q1: which one correct to change the address of an element to a new object's address?
arryM[ind] = newm; // this correct to pass and reset a new address for pointer?
arryM[ind] = &newm; // or is this correct, or does this just set the object pointed by array element instead of the array element's address?
*arryM[ind] = newm; // or do I need to dereference the pointer rep by array element first?
&arryM[ind] = &newm; // or is this correct??
}
...
// Q2: is it easier to return a pointer or address for this function?
M & Foo::getM(int ind) {
M *out;
// Q3: which one of following correct to get correct address value to return?
out = arryM[ind]; // get address to M obj pointed by pointer array elem
out = *arryM[ind]; // is "arryM[ind]" == "*ptr"?? if so how to get to "ptr"?
out = &arryM[ind]; // is this way to get to "ptr" so addresses passed?
return out;
}
}
void main() {
M *op1;
M *op2;
M *sol;
Foo mstorage; // and assume already got valid M objects pointed to by arryM[] elements
...
// Q4: which one correct?
op1 = mstorage.getM(x); // x being the correct and valid int index pos
op1 = *mstorage.getM(x); // so address and not object pointed to is passed?
*op1 = mstorage.getM(x);
op2 = mstorage.getM(y);
... // perform some operations using op1 and op2 M functions
int size = op1->getDim() + op2->getDim();
sol = new M(size, name); // no default constructor--M objects need a size parameter
...// perform/set values of sol based upon op1, op2 values
// Q5: this is correct to pass the address for sol object created, right?
if (<sol already exists>) mstorage.replace(indx, *sol);
else mstorage.add(*sol);
}
所以我从代码示例中提取的 5 个主要问题如下,Q1、Q3、Q4 对我来说是最重要/最令人困惑的:
Q1(重要):如果 array[i] 返回一个指针 *n,那么我们如何取消对“array[i]”的引用,使其看起来像“n”,这样我们就可以得到“n=p”,其中“*p”有一个外部创建的对象的地址。此外,其中 "*p" 通过带有 type& 参数的函数调用传递。
Q2:在给定的上下文中,在函数中返回指针还是地址更好?或者更改上下文以使用一种函数返回类型而不是另一种更容易?
Q3(重要):如果我们要返回一个地址,正确的方法是让“array[i]”(基于与 Q1 相同的假设)成为“n”中包含的地址而不是“*”表示的对象n”?
Q4(重要):如果函数返回地址&,那么本地创建的指针*p 是否能够通过“p = obj.funcretaddress()”接收地址?我看到了一些带有双打的示例代码,但这让我感到困惑:“双小时= funcreturningaddress()”。
Q5:只是仔细检查一个函数参数是否接受“obj &x”并且我们在本地创建一个“obj *y”,在函数调用中我们将传递“function(*y)”,然后在函数范围内传递“obj *n = &x" 以便由 array[i] 表示的指针可以获取本地创建的 obj 的正确地址。
非常感谢,因为我已经编译和调整了几天,试图从网络上获取具有 int 和 double 数据类型的示例并将它们应用于创建的类对象时感到困惑。
我很抱歉,如果有任何不清楚的地方请告诉我!
编辑:非常感谢,只是想澄清第四季度:
int a = 2;
int *b;
b = &a;
*b = 3;
int c = 4;
b = func(c); // *b now points to c, and value is 5?
*b = func(c); // *b value is updated to 5, and a therefore also now 5??
...
int & func(int &d) {
d++;
return &d; // correct, or wrong as &&d is returned?
return d; // and the & is applied to the var d?
}