C++类的 std::string 属性在初始化后显示为空字符串

发布于 2025-01-17 02:50:50 字数 861 浏览 2 评论 0原文

所以我有一个非常直接的作业,包括创建一个学生班级,该学生班级有一个名称和 3 个成绩作为属性,以及一个计算最终成绩并将名称和最终成绩分别附加到 2 个向量的方法,问题来了当我尝试将名称附加到向量时,因为它附加为空字符串,但调试器显示该学生类的实例(“校友”类)实际上有一个名称。

我将在下面留下代码,

class libroDeClases {
public:
    vector<string> nombres;
    vector<float> notasDef;
};

class Alumno {
private:
    string nombre;
    float n1, n2, n3;
    float notaDef;

public:
    Alumno(string nombre, float x, float y, float z) {
        nombre = nombre;
        n1 = x;
        n2 = y;
        n3 = z;    }
    void calcularNota(libroDeClases L) {
        float nd = (n1 + n2 + n3) / 3;
        notaDef = nd;
        L.notasDef.push_back(nd);
        L.nombres.push_back(nombre);
    } 

int main() {
    libroDeClases Libro;
    Alumno a1("Oscar", 4.0, 4.7, 5.5);
    a1.calcularNota(Libro);

谢谢您的帮助!

编辑:我添加了“Libro”类以使代码编译,我忘记提供它对此感到抱歉。

So i have a pretty straight foward homework that consist in creating a student class that has a name and 3 grades as attributes and a method to caluculate the final grade and append the name as well as the final grade to 2 vectors respectively, the problem comes up when i try to append the name to the vector as its appended as an empty string, but the debugger shows the instance of that student class (the "Alumno" class) has actually a name.

i'll leave you the code below,

class libroDeClases {
public:
    vector<string> nombres;
    vector<float> notasDef;
};

class Alumno {
private:
    string nombre;
    float n1, n2, n3;
    float notaDef;

public:
    Alumno(string nombre, float x, float y, float z) {
        nombre = nombre;
        n1 = x;
        n2 = y;
        n3 = z;    }
    void calcularNota(libroDeClases L) {
        float nd = (n1 + n2 + n3) / 3;
        notaDef = nd;
        L.notasDef.push_back(nd);
        L.nombres.push_back(nombre);
    } 

int main() {
    libroDeClases Libro;
    Alumno a1("Oscar", 4.0, 4.7, 5.5);
    a1.calcularNota(Libro);

thank you for your help!

Edit: i added the "Libro" class in order to make the code compile, i forgot to provide it sorry about that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏日落 2025-01-24 02:50:50

正如用户 Taekahn 在评论中所说,我使用了 This -> 现在它完美地附加了它。

谢谢。

As the user Taekahn said in a comment, i used This -> and it now appends it perfectly.

Thank you.

∞觅青森が 2025-01-24 02:50:50

如果通过引用 calularNota 传递对象,则字符串将成功打印。如果您只是按值传递,则会创建对象的副本,但不会更改原始对象的值: https://godbolt.org/z/fGzWvzW1b

If you pass the object by reference to calcularNota then the string gets printed successfully. If you just pass by value, a copy of the object gets made but doesn't change the value of the original object: https://godbolt.org/z/fGzWvzW1b

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文