【发布时间】:2023-04-01 05:35:01
【问题描述】:
#include<vector>
using namespace std;
struct x{
vector<int> y;
};
void magic(struct x& d)
{
d.y[0] = 5;
}
int main() {
struct x d;
d.y = {1,2,3};
struct x* z = &d;
magic(*z);
cout<<z->y[0];
return 0;
}
此代码是否有效以及如何?我们可以将 *z 传递给需要 c++ 引用的函数吗?
【问题讨论】:
-
该函数引用了
x,而您传递给它的是x。这类似于x &d= *z;。为什么你认为这不起作用? -
...或者更一般地说,
d和*z之间为什么会有任何区别? -
在C语言中,你需要做
struct x d;。在C++中,只需要x d;。 -
#include <bits/stdc++.h> using namespace std;- No, no, no,不要永远那样做。
标签: c++ pointers reference pass-by-reference