【问题标题】:Segmentation fault during runtime of console code in C++C++中控制台代码运行时的分段错误
【发布时间】:2019-04-15 19:03:47
【问题描述】:

我正在尝试制作一个简单的控制台学生详细信息显示系统,其中有 2 个班级,班级学生(基类)具有名称和注册号的成员变量,班级学生运动员(派生班级)具有运动类型字符串。 代码编译成功,但在运行时只询问学生详细信息,但不会像我调用 identify() 函数时所期望的那样显示详细信息。 在代码块上,错误可能不会显示,但在 https://www.onlinegdb.com/online_c++_compiler 等在线编译上,它表明代码中存在分段错误。 请在必要时提供帮助。

我的代码完全(整体)如下:

#include <iostream>
using namespace std;

/**Base class**/
class student
{
protected:
    string studName, studRegNum;
public:
    student(string stdName, string regNo);
    /**To define friendly class that is
    Common to both classes**/
    friend void identify();
};
/**constructor for class student**/
student::student(string stdName, string regNo)
{
    studName = stdName;
    studRegNum = regNo;
}
/**Derived class**/
class studentAthlete : public student
{
private:
    string member_sport;
public:
    /**To create constructor for class studentAthlete within class**/
    studentAthlete(string student_sport):student(studName, studRegNum)
    {
        member_sport = student_sport;
    }
    /**To define friendly class that is
    Common to both classes**/
    friend void identify();
};

/**To display student information**/
void identify()
{

    studentAthlete sa(sa.member_sport);
    cout<<"Student Name: "<<sa.studName<<endl;
    cout<<"Student Registration Number: "<<sa.studRegNum<<endl;
    cout<<"Student Sport: "<<sa.member_sport<<endl;

}

int main()
{
    string StudentName, StudentRegistrationNo, StudentSport;
    /**To get & set student name from user**/
    cout<<"Enter student name: "<<endl;
    cin>>StudentName;

    /**To get & set Student Registration No from user**/
    cout<<"Enter Student Registration No: "<<endl;
    cin>>StudentRegistrationNo;

    /**To get & set Student Sport from user**/
    cout<<"Enter Student Sport: "<<endl;
    cin>>StudentSport;

    /**To pass student values to their respective constructors**/
    student st(StudentName,StudentRegistrationNo);
    studentAthlete sa(StudentSport);

    /**To display student information**/
    identify();
    return 0;
}

【问题讨论】:

  • 这行应该是什么意思 studentAthlete sa(sa.member_sport);
  • 派生类继承不是这样工作的
  • @user463035818 因为你不能单独使用 studentAthlete sa 创建一个对象,我不得不将 sa.member_sport 传递给构造函数,否则我会收到错误“没有匹配函数调用'studentAthlete: :studentAthlete()' "
  • 帮自己一个忙,不要仅仅为了摆脱错误而编写代码。您的代码有几种未定义行为的情况,实际上我非常困惑如何在没有警告/错误的情况下进行编译
  • 快速总结:编译器错误意味着代码在语法上不正确,无法转换为可执行代码。编译代码不能保证代码在逻辑上是正确的并且做一些有用的事情。这就像将The Jabberwocky 输入英语解析器。结果是正确的,但爱丽丝说:“不知何故,它似​​乎让我的脑海充满了想法——只是我不完全知道它们是什么!然而,有人杀死了一些东西:这很清楚,无论如何。”

标签: c++ inheritance constructor runtime-error runtime


【解决方案1】:

您将未初始化的成员传递给 Student 构造函数。
这将导致未定义的行为。

您需要将姓名和号码参数添加到运动员的构造函数中,并将它们传递给Student

【讨论】:

  • identify() 函数中怎么样,因为这似乎是错误的来源
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
相关资源
最近更新 更多