c++程序输出一系列的数字而不是cout

c++ program outputs series of numbers instead of cout

本文关键字:cout 数字 程序 输出 一系列 c++      更新时间:2023-10-16

我目前的任务是创建一个简单的

参加的学生班

first name 
last name
student ID number 

并将名称作为单个字符串和他/她的ID号输出。该程序还必须统计每个学生并输出学生总数。在这个项目中,我有4名学生。

我已经创建了这个程序,如下所示。一切都编译正确并运行,但我的输出很奇怪。它没有给我学生的身份证和姓名,而是给了我"-858993460"的号码。我不知道为什么我的程序会这样做,在互联网上长时间搜索对我没有太大帮助。

学生.h

#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string firstName;
string lastName;
int id;
string name;
public:
static int numberOfStudents;
Student();
Student(string theFirstName, string theLastName, int theID);
string getName();
int getID();
};

学生.cpp

#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
//initialize numberOfStudents to 0
int Student::numberOfStudents = 0;
//initialize default constructor
Student::Student()
{
numberOfStudents++;
}
//initialize overloaded constructor
Student::Student(string theFirstName, string theLastName, int theID)
{
theFirstName = firstName;
theLastName = lastName;
theID = id;
numberOfStudents++;
}
//getName
string Student::getName()
{
return firstName += lastName;
}
//getID
int Student::getID()
{
return id;
}

main.cpp(这是我的驱动程序文件)

#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Student st1("Hakan", "Haberdar", 1234), st2("Charu", "Hans", 2345), st3("Tarikul", "Islam", 5442), st4;
cout << "We created " << Student::numberOfStudents<<" student objects." << endl;
cout << st1.getID()<<" "<<st1.getName()<<endl;
cout << st2.getID()<<" "<<st2.getName()<<endl;
cout << st3.getID()<<" "<<st3.getName()<<endl;
cout << st4.getID()<<" "<<st3.getName()<<endl;
system("pause");
};

我的输出应该是这样的:我们创建了4个学生对象。1234 Hakan Haberdar2345查鲁汉斯5442塔里库尔伊斯兰教0

这就是我的输出:我们创建了4个学生对象。-858993460-858993460-858993460-858993460

我认为我的问题与我的getName()函数有关,但我不确定,也不知道该尝试什么。

Student::Student(string theFirstName, string theLastName, int theID)
{
theFirstName = firstName;
theLastName = lastName;
theID = id;
numberOfStudents++;
}

你的作业错了。您正在将尚未初始化的成员分配给参数。相反,你应该有:

Student::Student(string theFirstName, string theLastName, int theID)
{
firstName = theFirstName;
lastName = theLastName;
id = theID;
numberOfStudents++;
}

如果您使用的是成员初始化列表,则可以避免此错误:

Student::Student(string theFirstName, string theLastName, int theID)
: firstName(theFirstName), lastName(theLastName), id(theID)
{
numberOfStudents++;
}

不确定以下是否是问题的原因,但这似乎是错误的。。。

return firstName += lastName;

这样做的目的是通过在名字后面附加姓氏来修改名字,然后返回修改后的字符串。

我想你是想做一些类似的事情

return firstName << ' ' << lastName;

将代码更改为.

Student::Student(string theFirstName, string theLastName, int theID)
{
firstName = theFirstName;
lastName = theLastName;
id = theID;
numberOfStudents++;
}

您的代码返回id的值!其未被初始化。因此,代码将返回垃圾。