0

除了 get 和 set name 函数外,我的编码中的所有内容都有效。当我调用 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

这是我的函数和类,.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;
}
4

2 回答 2

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

你肯定看到了那里的问题。提示,赋值将右边的东西复制到左边的东西。

于 2012-08-12T07:29:32.050 回答
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;
}
于 2012-08-12T07:30:04.667 回答