c++ - 我的字符串不是从私有(private)变量复制的

标签 c++ string get set

除了 get 和 set name 函数外,我的代码中的所有内容都有效。当我调用 getName 时,它​​打印为空白。我尝试了几种不同的解决方案,但唯一有效的方法实际上是将 fullName 字符串保存在 main 中,并从那里调用它。就好像它不允许我调用变量,因为它们是私有(private)的。

这是我的 .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;
}

最佳答案

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

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

关于c++ - 我的字符串不是从私有(private)变量复制的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11920449/

相关文章:

c - 用于存储立即字符串的内存 session ,在 C 中

jQuery 获取元素后带有通配符内容的文本并移动它

c++ - 包装 PropertySheet;如何处理回调?

c++ - 如何返回结构数组

c++ - 副作用 C++ vector 复制和删除

javascript - 如何获取查询字符串中包含的 url

ruby - 将 curl header 格式转换为 Ruby 的 header 格式

c++ - OLE:多个 OLE 对象的共享 IStorage?

java - 编译时性能成本

c - 修改并替换C中char数组中的值