【问题标题】:How do you use strings in a class?如何在课堂上使用字符串?
【发布时间】:2014-04-04 04:18:14
【问题描述】:

好吧,我已经研究了一段时间,但我似乎无法弄清楚。

#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,但是当我运行我的程序时它崩溃了,运行后没有告诉我错误。 任何帮助将不胜感激!

【问题讨论】:

  • 谢谢你们,我希望我早点问这个问题:p

标签: c++ string class


【解决方案1】:

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

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

这会分配一个学生指针数组。它不分配 Student 对象的数组。因此,在这行代码中,您有一个包含 5 个无效指针的数组。当您尝试像指向学生对象一样访问它们时,这是一个问题,在这里:

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 对象的一维动态集合,请使用标准库中的 sequence container,例如 std::vector

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2020-11-30
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-03
        相关资源
        最近更新 更多