2015-10-17 55 views
0

不知道我現在在哪裏,試圖找出它。我需要在print()const中初始化成員,因爲它給了我隨機的亂碼。無論我嘗試做什麼,它似乎都不起作用。不知道該怎麼辦。任何人都可以幫我一把嗎?從另一個函數中初始化print()中的成員

*編輯:在代碼的其餘部分添加。當我第一次提交時忘了它。

Student.cpp

#include "student.h" 


//implement the required 3 functions here 


Student::Student(const char initId[], double gpa) 
{ 
    // initialize a newly created student object with the passed in value 



} 

bool Student::isLessThanByID(const Student& aStudent) const 
{ 
// compare the current student object with the passed in one by id. 
if (strcmp(id, aStudent.id) > 0) 
{ 
    return true; 
} 
else 
{ 
    return false; 
} 


} 

bool Student::isLessThanByGpa(const Student& aStudent) const 
{ 
// compare the current student object with the passed in one by gpa 
if (gpa < aStudent.gpa) 
{ 
    return true; 
} 
else 
{ 
    return false; 
} 

} 

void Student::print() const 
{ 
cout << id << '\t' << gpa << endl; 
} 

student.h

#ifndef STUDENT_H 
#define STUDENT_H 

#include <iostream> 
using namespace std; 

class Student 
{ 
public: 
Student(const char initId[], double gpa); 
bool isLessThanByID(const Student& aStudent) const; 
bool isLessThanByGpa(const Student& aStudent) const; 
void print()const; 
private: 
const static int MAX_CHAR = 100; 
char id[MAX_CHAR]; 
double gpa; 
}; 
#endif 

app.cpp

#include "student.h" 

int main() 
{ 
Student s1("G10", 3.9); 
Student s2("G20", 3.5); 

s1.print(); 
s2.print(); 

if(s1.isLessThanByID(s2)) 
{ 
    cout << "about right!" << endl; 
} 
else 
{ 
    cout << "uhmm ..." << endl; 
} 
if(!s1.isLessThanByGpa(s2)) 
{ 
    cout << "about right!" << endl; 
} 
else 
{ 
    cout << "uhmm ..." << endl; 
} 

system("pause"); 
return 0; 
} 
+0

'初始化一個新創建的學生對象中value' –

+0

過去了如果你在一個類中的非靜態成員變量和唐不初始化它們,它們的值將是*不確定的,並且使用它們(除了初始化它們)將導致*未定義的行爲*。我建議你搜索並閱讀*構造函數初始化列表*。 –

回答

1

中沒有任何代碼,設置的Student::idStudent::gpa值。您的構造函數具有參數initIdgpa;你應該將這些複製到你的對象中。根據您所提供的Student的聲明,這事要適當:

Student::Student(const char initId[], double gpa) : gpa(gpa) 
{ 
    strncpy(id, initId, Student::MAX_CHAR-1); 
    id[Student::MAX_CHAR-1] = '\0'; 
} 
+0

strcpy工作(但我必須使用strcpy_s)爲id和initId。然而,它不適用於全球一體化。 gpa在Student中設置爲double,在public.h中設置爲student.h。嘗試使用時,它會給我一個-9.2.5596e + 061而不是我的app.cpp中所需的值。 (3.9和3.5) – EdWar82

+0

你會得到什麼錯誤? Student :: gpa如何申報? – user3553031

+0

它在我的Student :: Student(const char initId [],double gpa)和我的student.h中聲明。 \t bool isLessThanByID(const Student&aStudent)const; \t bool isLessThanByGpa(const Student&aStudent)const; \t void print()const; private: \t const static int MAX_CHAR = 100; \t char \t id [MAX_CHAR]; \t double \t gpa; }; 這是內存泄漏還是別的? (對不起,仍然在學習)。它給我的價值是 - 9.25596e + 061而不是我所需要的(3.9和3.5) – EdWar82

相關問題