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

C++如何将类成员string nome设为私有并在main函数正确访问

实现方法

C++中private修饰的类成员无法在类外部(比如main函数里)直接读写,你已经给idade、matricula两个私有成员写了对应的公有set/get方法,给nome加一套同逻辑的方法即可。

修改步骤

  • 调整Aluno类定义
    • 把string nome;移动到private区块,和其他私有成员放在一起
    • 在public区块新增setNome()(负责给nome赋值)和getNome()(负责读取nome的值)两个公有成员方法,逻辑和你已经写好的setIda()/getIda()、setMatr()/getMatr()完全一致
  • 修改main函数里的访问逻辑
    • 所有直接读写->nome的代码,替换成调用对应的set/get方法即可

修改后的完整可运行代码如下:

#include <iostream>
#include <string>

using namespace std;

class Aluno
{
public:
    // nome的公有set方法
    void setNome(string name)
    {
        // 可按需添加校验逻辑,比如判断名字长度符合要求、非空等
        nome = name;
    }
    // nome的公有get方法
    string getNome()
    {
        return nome;
    }

    void setIda(int age)
    {
        if (age > 0 && age < 60)
            idade = age;
        else
            idade = 0;
    }
    int getIda()
    {
        return idade;
    }
    void setMatr(int matr)
    {
        if (matr > 0 && matr <= 1000)
            matricula = matr;
        else
            matricula = 0;
    }
    int getMatr()
    {
        return matricula;
    }
private:
    string nome; // 移动到私有成员区块
    int matricula;
    int idade;
};

int main()
{
    Aluno *novo_aluno1 = new Aluno();
    Aluno *novo_aluno2 = new Aluno();

    // 赋值时调用setNome
    novo_aluno1->setNome("John Smith");
    novo_aluno1->setIda(32);
    novo_aluno1->setMatr(999);

    novo_aluno2->setNome("Mary Smith");
    novo_aluno2->setIda(21);
    novo_aluno2->setMatr(998);

    // 读取时调用getNome,同时修正了原代码中换行符位置错误的问题
    cout << "\nNome: " << novo_aluno1->getNome() << "\n";
    cout << "Idade: " << novo_aluno1->getIda() << "\n";
    cout << "Matricula: " << novo_aluno1->getMatr() << "\n";

    cout << "\nNome: " << novo_aluno2->getNome() << "\n";
    cout << "Idade: " << novo_aluno2->getIda() << "\n";
    cout << "Matricula: " << novo_aluno2->getMatr() << endl;

    // 释放new申请的堆内存,避免内存泄漏
    delete novo_aluno1;
    delete novo_aluno2;

    return 0;
}

入门提示:这种“私有成员+公有的set/get方法”的写法是面向对象封装特性最基础的实现形式,你可以在set方法里加入参数合法性校验逻辑,避免非法值写入成员变量,这也是不建议把类成员直接设为public的核心原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:30:53