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

标签 c++ output

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

学生类(class)

first name 
last name
student ID number 

从一个对象中输出名字作为一个字符串和他/她的身份证号码。该程序还必须计算每个学生并输出学生总数。在这个项目中,我有 4 个学生。

我已经创建了程序,如下所示。一切都正确编译并运行,但我的输出很奇怪。它没有给我学生的 ID 和姓名,而是给了我号码“-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关 第2345章 第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++;
}

关于c++程序输出一系列数字而不是cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21868480/

相关文章:

c++ - 将类导出到 DLL

c++ - 如何将字符串数组的值分配给 "Name"+ #,例如。名称 1、名称 2、名称 3 等。C++

c++ - 使用 -> 获取 gsl_matrix 结构指针

python - 有人可以解释为什么我的打印语句没有将两个变量打印在一行上吗?

powershell - 从输出中删除空行

C++ 问号输出

c++ - SFML 生成等距图 block

c++ - 无法理解包括头文件

function - Julia - 定义一个输出函数的函数

谁能检查程序并告诉我如何获得正确的输出?