【问题标题】:Modifying "Const Char Pointers" in C++在 C++ 中修改“常量字符指针”
【发布时间】:2020-02-26 06:24:52
【问题描述】:

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

【问题讨论】:

  • 您的const char* 重载应该与您的其他重载完全一样。试试看。
  • 不起作用,您的意思是将参数类型更改为int 或float
  • 就像您为int 使用int temp =x; x=y; y=temp; 一样,您应该为const char * 使用const char* temp =x; x=y; y=temp;。
  • 谢谢!但你能解释一下为什么会这样吗?
  • @NathanOliver-ReinstateMonica(越早越好)Bishoy,发生的事情(取决于你的机器 x86_64 等)是 sizeof (int) 只是 sizeof(a_pointer) 的 1/2,(通常是 @在 64 位系统上,987654333@ 是 4 字节,a_pointer 是 8 字节)。当您使用 int help = *x;(应该只是 x,而不是 *x 和 char)时,help 不够大,无法容纳完整的地址,所以在您的 @ 987654340@,str2 指针交换。另外,启用编译器警告并且在编译时不接受代码,直到它没有警告地编译(-Wall -Wextra -pedantic 用于 gcc/clang 或/W3 用于 VS)

标签: c++ pointers constants pass-by-reference


【解决方案1】:

按照 cmets 的建议:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2010-10-15
    • 2011-01-31
    • 1970-01-01
    • 2013-08-02
    • 2010-10-03
    相关资源
    最近更新 更多