Moe*_*oeb 1 c++ swap c-strings
下面的代码给我一个编译错误,但我不明白我做错了什么.对于提出这么愚蠢的问题很抱歉.
$ 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*&)’
$
Run Code Online (Sandbox Code Playgroud)
数组不能被修改,它们只是衰减到临时指针,它们不是真正的指针,不能交换.当您尝试将从数组获得的临时指针绑定到非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";
Run Code Online (Sandbox Code Playgroud)
或者,如果您可以更改函数的原型,请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";
Run Code Online (Sandbox Code Playgroud)