2012-08-12 26 views
0

我的編碼中的所有東西除get和set名稱函數外都有效。當我調用getName時,它打印空白。我已經嘗試了幾種不同的解決方案,但唯一有效的方法是將fullName字符串保存在main中,然後從那裏調用它。這就好像它不讓我稱這些變量是因爲它們是私人的。我的字符串不是從私有變量複製

這是我的.cpp文件。

#ifndef STUDENT_H 
#define STUDENT_H 
#include <iostream> 
#include <string> 

#include "Student.h" 

using namespace std; 

int main() 
{ 
    //for student name 
    string firstName; 
    string lastName; 
    string fullName; 


//student name 

cout << "Please enter your students first name" << endl; 
cin >> firstName; 
cout << "firstName = " << firstName << endl; 


cout << "Please enter your students last name" << endl; 
cin >> lastName; 
cout << "lastName = " << lastName << endl; 

aStudent.setName(firstName, lastName); 
fullName = aStudent.getName(); 

cout << "Your students name is : "; 
cout << fullName << endl; 

} 
#endif 

這裏是我的函數和class.h文件。

#include <iostream> 
#include <string> 
#include <conio.h> 

using namespace std; 
class Student 
{ 

private: 
string fName; 
string lName; 

public: 
string getName(); 
void setName(string firstName, string lastName); 

}; 

string Student::getName() 
{ 
return fName + " " + lName; 
} 
void Student::setName(std::string firstName, std::string lastName) 
{ 
firstName = fName; 
lastName = lName; 
} 
+0

您的代碼結構很混亂,頭文件應該只有方法聲明。 – nikhil 2012-08-12 07:29:43

回答

8
void Student::setName(std::string firstName, std::string lastName) 
{ 
    firstName = fName; 
    lastName = lName; 
} 

當然你看到問題在那裏。提示,分配將右邊的東西複製到左邊的東西上。

+0

哇,我肯定花了太多時間看整個程序錯過了這樣的事情。謝謝*臉紅*,太尷尬了! – trueCamelType 2012-08-13 12:41:51

2
void Student::setName(std::string firstName, std::string lastName) 
{ 
    firstName = fName; // you're assigning the local firstName to your class instance's 
    lastName = lName; // variable; reverse this and try again 
} 

// ... 
void Student::setName(std::string firstName, std::string lastName) 
{ 
    fName = firstName; 
    lName = lastName; 
} 
0

您正在將類成員變量分配給方法參數,這意味着您將變量賦值放在前面。

這應該工作。

void Student::setName(std::string firstName, std::string lastName) 
{ 
    firstName = fName; 
    lastName = lName; 
} 
相關問題