C++类的 std::string 属性在初始化后显示为空字符串
所以我有一个非常直接的作业,包括创建一个学生班级,该学生班级有一个名称和 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如用户 Taekahn 在评论中所说,我使用了
This ->
现在它完美地附加了它。谢谢。
As the user Taekahn said in a comment, i used
This ->
and it now appends it perfectly.Thank you.
如果通过引用 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