修改C++中的"Const Char Pointers"

Modifying "Const Char Pointers" in C++

本文关键字:Char Pointers Const 修改 中的 C++      更新时间:2023-10-16

我正在做一个程序,通过引用测试交换一些东西。我设法使代码中的前两个函数工作,但无法更改第三个函数中的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;
}