gpt4 book ai didi

c++ - 如何使用 C++ 引用交换两个 C 风格的字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:19:29 24 4
gpt4 key购买 nike

下面的代码给我一个编译错误,但我不明白我做错了什么。抱歉问了这么愚蠢的问题。

$ cat swapcstrings.cc
#include <iostream>

void swap(char*& c, char*& d) {
char* temp = c;
c = d;
d = temp;
}

int main() {
char c[] = "abcdef";
char d[] = "ghijkl";
std::cout << "[" << c << "," << d << "]\n";
swap(c, d);
std::cout << "[" << c << "," << d << "]\n";
}
$ g++ swapcstrings.cc
swapcstrings.cc: In function ‘int main()’:
swapcstrings.cc:13: error: invalid initialization of non-const reference of type ‘char*&’ from a temporary of type ‘char*’
swapcstrings.cc:3: error: in passing argument 1 of ‘void swap(char*&, char*&)’
$

最佳答案

数组不能被修改,它们只是退化为临时指针,它们不是真正的指针,不能交换。数组的地址无法更改,当您尝试将从数组获得的临时指针绑定(bind)到非const 引用时,编译器会出错,这违反了语言规则。

声明数组,然后将两个指针交换给它们。

char a[] = "abcdef";
char b[] = "defghi";

char* aptr = a, *bptr = b;

std::cout << "[" << aptr << "," << bptr << "]\n";
swap(aptr, bptr);
std::cout << "[" << aptr << "," << bptr << "]\n";

或者如果你可以改变函数的原型(prototype),首先使用const char*:

void swap(const char*& c, const char*& d) {
const char* temp = c;
c = d;
d = temp;
}

const char* c = "abcdef", // These must be const char* because the arrays are
* d = "ghijkl"; // const char[N]

std::cout << "[" << c << "," << d << "]\n";
swap(c, d);
std::cout << "[" << c << "," << d << "]\n";

关于c++ - 如何使用 C++ 引用交换两个 C 风格的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771764/

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