[英]Modifying “Const Char Pointers” in C++
我正在做一个程序来测试通过引用交换一些东西。 我设法让我的代码中的前两个函数工作,但无法更改第三个 function 中的char *
。
我认为问题在于它是一个常量并且只对read-only
有效,这就是错误告诉我的,但是如何能够以这种方式使用它?
这是代码:
#include <iostream>
using namespace std;
void swapping(int &x, int &y)
{
int temp =x;
x=y;
y=temp;
}
void swapping(float &x, float &y)
{
float temp=x;
x=y;
y=temp;
}
void swapping(const char *&x,const char *&y)
{
int help = *x;
(*x)=(*y);
(*y)=help;
} // swap char pointers
int main(void) {
int a = 7, b = 15;
float x = 3.5, y = 9.2;
const char *str1 = "One";
const char *str2 = "Two";
cout << "a=" << a << ", b=" << b << endl;
cout << "x=" << x << ", y=" << y << endl;
cout << "str1=" << str1 << ", str2=" << str2 << endl;
swapping(a, b);
swapping(x, y);
swapping(str1, str2);
cout << "\n";
cout << "a=" << a << ", b=" << b << endl;
cout << "x=" << x << ", y=" << y << endl;
cout << "str1=" << str1 << ", str2=" << str2 << endl;
return 0;
}
正如评论中所建议的:
void swapping(const char*& x, const char*& y)
{
auto t = x;
x = y;
y = t;
}
现在您应该考虑使用模板:
template<typename Type>
void swapping(Type& a, Type& b)
{
auto t = a;
a = b;
b = t;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.