提问人:John C. 提问时间:10/31/2019 更新时间:11/1/2019 访问量:170
在 C++ 中修改“常量字符指针”
Modifying "Const Char Pointers" in C++
问:
我正在做一个程序来测试通过引用交换一些东西。
我设法让代码中的前两个函数工作,但无法更改第三个函数。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;
}
答:
1赞
Tobias Wollgam
11/1/2019
#1
正如评论中所建议的:
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;
}
评论
const char*
int
float
int temp =x; x=y; y=temp;
int
const char* temp =x; x=y; y=temp;
const char *
sizeof (int)
sizeof(a_pointer)
int
a_pointer
int help = *x;
x
*x
char
help
str1
str2
-Wall -Wextra -pedantic
/W3