如何在类中使用字符串

How do you use strings in a class?

本文关键字:字符串      更新时间:2023-10-16

好吧,我已经为此工作了一段时间,但我似乎无法弄清楚。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "student.h"
using namespace std;
int numofstudents = 5;
Student ** StudentList = new Student*[numofstudents];
string tempLname = "smith";
StudentList[0]->SetLname(tempLname);

#include<iostream>
#include <string>
using namespace std;
class Student {
public:
  void SetLname(string lname);
  void returnstuff();
protected:
  string Lname;
};
#include <iostream>
#include "student.h"
#include <iomanip>
#include <cctype>
#include <cstring>
#include <string>
using namespace std;
void Student::SetLname(string lname) {
  Lname = lname;
}

我想做的只是将Lname设置为 smith但是当我运行我的程序时,它会崩溃而不会在运行后告诉我错误。任何帮助将不胜感激!

您的问题与使用字符串无关。这与使用指针有关。

Student ** StudentList=new Student*[numofstudents];

这将分配一个学生指针数组。它不分配 Student 对象的数组。因此,从这行代码开始,您有一个包含 5 个无效指针的数组。当您尝试访问它们时,这是一个问题,就好像它们指向 Student 对象一样,如下所示:

StudentList[0]->SetLname(tempLname);

为了使该行有效,StudentList[0]首先需要指向有效的Student对象。您可以将其设置为现有对象:

Student st;
StudentList[0] = &st;

或者,您可以分配一个新对象:

StudentList[0] = new Student;

否则,摆脱额外的间接级别:

Student * StudentList=new Student[numofstudents];
...
StudentList[0].SetLname(tempLname);

但你到底为什么要这样做呢?如果需要Student对象的一维动态集合,请使用标准库中的序列容器,例如 std::vector

Student ** StudentList=new Student*[numofstudents];更改为

Student ** StudentList=new Student*[numofstudents];
for(int i = 0; i<numofstudents; i++)
    StudentList[i] = new Student();

您创建了指向 Student 的指针数组,但数组的元素未初始化,因此取消引用任何元素,特别是 [0] 都会导致崩溃。使用 "std::vector StudentList(numofstudents);",对代码 "StudentList[0] 进行微小更改。SetLname(tempLname);"