You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中无法打印类成员字符串问题求助

问题分析与修复方案

你的代码存在几个关键问题,直接导致了修改无效和输出乱码,下面逐一说明并给出修复方案:

1. 拼写错误导致返回无效内存地址

channel类的getName()方法中,错误返回了未定义的变量nom,但类的成员变量实际是name。这会让函数返回随机内存地址,打印时自然出现乱码。

2. 返回值拷贝导致修改无法作用到原对象

Case::get_channel()返回的是channel对象的值拷贝,而非原数组中对象的引用或指针。这意味着b1.get_channel(4).setName("food")修改的是临时生成的副本,原数组里的channel对象完全没被改动。

3. 使用malloc分配类对象数组的不规范问题

malloc仅分配内存空间,不会调用类的构造函数。虽然当前channel的构造函数是空的,但C++中应当使用new[]创建对象数组,它会自动为每个元素调用构造函数,保证对象正确初始化。

4. 非标准的main函数写法

C++标准规定main函数的返回类型必须是int,void main()属于非标准写法,需要修正。


修正后的代码

file.hpp

class channel
{
    char name[50];

public:
    channel();
    void setName(const char*); // 参数改为const char*,更安全
    const char *getName();     // 返回值加const,避免意外修改
}; // 注意添加类定义结束的分号

class Case
{
    char name[50];
    channel *channels;

public:
    Case();
    ~Case(); // 添加析构函数,释放动态分配的内存
    channel& get_channel(int); // 返回引用,而非值拷贝
};

file.cpp

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include "file.hpp"

channel::channel()
{
    // 初始化name为空字符串,避免垃圾值
    memset(name, 0, sizeof(name));
}

void channel::setName(const char* c)
{
    // 使用strncpy更安全,避免缓冲区溢出
    strncpy(name, c, sizeof(name) - 1);
    name[sizeof(name)-1] = '\0'; // 确保字符串以'\0'结尾
}

const char* channel::getName()
{
    return name; // 修正拼写错误,返回正确的成员变量
}

Case::Case()
{
    // 使用new[]创建对象数组,自动调用构造函数
    channels = new channel[14];
}

Case::~Case()
{
    // 释放动态分配的数组
    delete[] channels;
}

channel& Case::get_channel(int nb)
{
    // 返回原对象的引用
    return channels[nb];
}

int main() // 修正为标准的int返回类型
{
    Case b1;
    b1.get_channel(4).setName("food");
    printf("%s", b1.get_channel(4).getName());
    return 0;
}

内容的提问来源于stack exchange,提问作者Nemul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 15:13:26