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

时间:2014-02-19 00:25:11

标签: c++ output

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

学生班级 采用

first name 
last name
student ID number 
从对象

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

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

Student.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();
};

Student.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 Charu Hans 5442塔里库尔伊斯兰教 0

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

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

3 个答案:

答案 0 :(得分:3)

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++;
}

答案 1 :(得分:0)

不确定以下是否是您的问题的原因,但似乎确实有误......

return firstName += lastName;

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

我认为你打算做一些像

这样的事情
return firstName << ' ' << lastName;

答案 2 :(得分:0)

将您的代码更改为。

  Student::Student(string theFirstName, string theLastName, int theID)

{
    firstName = theFirstName;
    lastName = theLastName;
    id = theID;
    numberOfStudents++;
}

您的代码返回id的值!哪个没有初始化。 所以代码将返回垃圾。