我的編碼中的所有東西除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;
}
您的代碼結構很混亂,頭文件應該只有方法聲明。 – nikhil 2012-08-12 07:29:43