在 C++ 中修改“常量字符指针”

Modifying "Const Char Pointers" in C++

提问人:John C. 提问时间:10/31/2019 更新时间:11/1/2019 访问量:170

问:

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

评论

0赞 NathanOliver 10/31/2019
您的重载应该看起来与其他重载完全相同。试一试。const char*
0赞 John C. 10/31/2019
不起作用,您的意思是将参数类型更改为 orintfloat
0赞 NathanOliver 10/31/2019
就像你对 's 所做的那样,你应该使用 's。int temp =x; x=y; y=temp;intconst char* temp =x; x=y; y=temp;const char *
0赞 John C. 10/31/2019
谢谢!但你能解释一下为什么会这样吗?
1赞 David C. Rankin 10/31/2019
@NathanOliver-ReinstateMonica(越早越好) Bishoy,发生的事情(取决于您的机器x86_64等)只有 1/2 ,(通常为 4 字节,在 8 位系统上为 64 字节)。当您使用 (should be just , not a ) 时,它不够大,无法容纳完整的地址,因此在指针交换中,事情会偏离轨道。此外,启用编译器警告,并且在编译之前不接受代码(对于 gcc/clang 或 VS)sizeof (int)sizeof(a_pointer)inta_pointerint help = *x;x*xcharhelpstr1str2-Wall -Wextra -pedantic/W3

答:

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;
}