搜尋

首頁  >  問答  >  主體

C++代码一直是执行错误

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class citizen
{
private:
    char name[20];
    char sex;
    int age;
public:
    citizen();
    citizen(char name[], char sex, int age);
    virtual void show();
    ~citizen()
    {
        ofstream myout;
        myout.open("a.txt", ios::out | ios::app);
        cout << "this is the first destruction function!" << endl;
        myout << "this is the first destruction function!" << endl;
    }
};
class student :public citizen
{
private:
    char number[20];
    char classname[20];
public:
    student(char name[], char sex, int age, char number[], char classname[]) :citizen(name, sex, age)
    {
        strcpy_s(this->number, number);
        strcpy_s(this->classname, classname);
    }
    void show();
    ~student()
    {
        ofstream myout;
        myout.open("a.txt", ios::out | ios::app);
        cout << "this is the second destruction function!" << endl;
        myout << "this is the second destruction function!" << endl;
    }
};
citizen::citizen(char name[], char sex, int age)
{
    strcpy_s(this->name, name);
    this->sex = sex;
    this->age = age;
}
void citizen::show()
{
    ofstream myout;
    myout.open("a.txt", ios::out | ios::app);
    cout << "姓名为:" << name << endl;
    cout << "性别为:" << sex << endl;
    cout << "年龄为:" << age << endl;
    myout << "姓名为:" << name << endl;
    myout << "性别为:" << sex << endl;
    myout << "年龄为:" << age << endl;
}
void student::show()
{
    ofstream myout;
    myout.open("a.txt", ios::out | ios::app);
    citizen::show();
    cout << "学号为:" << number << endl;
    cout << "班级为:" << classname << endl;
    myout << "学号为:" << number << endl;
    myout << "班级为:" << classname << endl;
}
int main()
{
    ofstream myout;
    myout.open("a.txt", ios::out | ios::app);
    char name[20], number[20], classname[20];
    char sex;
    int age;
    citizen *c;
    cout << "请输入姓名,性别(男:m,女:f),年龄" << endl;
    myout << "请输入姓名,性别(男:m,女:f),年龄" << endl;
    cin >> name >> sex >> age;
    myout << name << '\t' << sex << '\t' << age << endl;
    c=&citizen(name, sex, age);
    cout << "公民类的输出:" << endl;
    myout << "公民类的输出:" << endl;
    c->show();
    cout << "请输入学号,班级" << endl;
    myout << "请输入学号,班级" << endl;
    cin >> number >> classname;
    myout << number << '\t' << classname << endl;
    c=&student(name, sex, age, number, classname);
    cout << "大学生类的输出:" << endl;
    myout << "大学生类的输出:" << endl;
    c->show();
    return 0;
}
巴扎黑巴扎黑2803 天前359

全部回覆(3)我來回復

  • 怪我咯

    怪我咯2017-04-17 13:19:17

    首先…既然用了函數就把頭檔寫上…

    #include <cstring>

    然後,這份程式碼在clang下編譯失敗

    如果在vs上可能能通過吧,手上沒有vs不知道。
    指向臨時變數的指標是未定義的,臨時變數隨時可能被銷毀,所以存取被回收的記憶體可能會發生錯誤

    以上

    回覆
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:19:17

    你好,下次提問請描述錯誤訊息。

    我在vs 2015下運行沒有問題。

    回覆
    0
  • 迷茫

    迷茫2017-04-17 13:19:17

    你這問題問的,程式碼一貼什麼都不解釋,那麼一長串程式碼你都不解釋一下你這是在幹嘛,怎麼個錯誤類型,想幫你都懶得看。 。

    回覆
    0
  • 取消回覆