首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C++中修改“常量字符指针”

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

Stack Overflow用户
提问于 2019-10-31 05:46:37
回答 1查看 79关注 0票数 0

我正在做一个程序,通过引用来测试交换一些东西。我设法让代码中的前两个函数正常工作,但无法更改第三个函数中的char *

我认为问题是它是一个常量,并且只对read-only有效,这就是错误告诉我的,但是如何能够以这种方式使用它呢?

代码如下:

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2019-11-01 22:15:31

正如评论中所建议的:

代码语言:javascript
复制
void swapping(const char*& x, const char*& y)
{
    auto t = x;
    x = y;
    y = t;
}

现在,您应该考虑使用模板:

代码语言:javascript
复制
template<typename Type>
void swapping(Type& a, Type& b)
{
    auto t = a;
    a = b;
    b = t;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58634095

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档