gpt4 book ai didi

c++ - 为什么我可以通过引用调用字符串文字而不是数组?

转载 作者:行者123 更新时间:2023-11-28 02:52:53 25 4
gpt4 key购买 nike

如果我不清楚问题,请查看下面的代码。为什么字符测试有效,而整数测试无效?我发现很难理解的字符串文字和数组之间的根本区别是什么?

using namespace std;

void fun(int &x)
{
cout << x << " okk" << endl;
}

void test (int* &a, int* &b) {
int* temp = a;
a = b;
b = temp;
//cout << *a << " " << &a << endl;
}

void test (char* &a, char* &b) {

cout << &a << " " << &b << endl;
char * temp = a;
a = b;
b = temp;
//cout << *a << " " << &a << endl;
}

int main()
{
char *s = "help";
char *t = "me";

char *u = "help";

cout << s << " " << t << " " << u << endl;

/*char *temp = s;
s = t;
t = temp;
*/

test (s,t);

cout << s << " " << t << endl;

int a[10] = {1,2,3,4,5,6,7,8,9,10};
int b[10] = {11,12,13,14,15,16,17,18,19,20};

cout << *a << " " << *b << endl;

test (a,b);

cout << *a << " " << *b;

}

最佳答案

一个 int[] 不是一个 int*,所以你不能传递一个 int[] 而一个 int*& reference 是预期的。但是,int[] 确实会降级为 int* 指针,因此您可以传递 int[]需要 int* 的地方。 & 引用有很大的不同。当您通过引用传递某些内容时,该内容必须与引用所指的数据类型相匹配。

关于c++ - 为什么我可以通过引用调用字符串文字而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22647460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com