我的编码中的所有内容都起作用,除了get和set name函数。当我调用getName时,它打印为空白。我尝试了一些不同的解决方案,但唯一有效的方法是将mainName字符串保存在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;
}
答案 0 :(得分:8)
void Student::setName(std::string firstName, std::string lastName)
{
firstName = fName;
lastName = lName;
}
你肯定在那里看到了问题。提示,赋值将右侧的东西复制到左侧的东西。
答案 1 :(得分: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;
}
答案 2 :(得分:0)
您正在将类成员变量分配给方法参数,这意味着您将变量赋值返回到前面。
这应该有效。
void Student::setName(std::string firstName, std::string lastName)
{
firstName = fName;
lastName = lName;
}