簡體   English   中英

C++ char 指針的 memcpy/strcpy 指向 class 成員 char 指針

[英]C++ memcpy/strcpy of char pointer to class member char pointer

我有一個自定義 class,我們稱它為“學生”和一個主要方法。 我正在實例化 class,只想 output class 的內容。

我的程序崩潰了: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

實際代碼

學生.h

#ifndef PROG2_STUDENT_H
#define PROG2_STUDENT_H

#include <iostream>

class Student
{
private:
    char *name;

    char *firstName;

    unsigned matriculationNumber;

    unsigned semester;

public:
    Student(char *name, char *firstName, unsigned matriculationNumber, unsigned semester);

    ~Student();

    friend std::ostream &operator<<(std::ostream &ostream, const Student &student);
private:
};

#endif

學生.cpp

#include <cstring>
#include "Student.h"

Student::Student(char *name, char *firstName, unsigned matriculationNumber, unsigned semester)
{
    std::strcpy(this->name, name);
    std::strcpy(this->firstName, firstName);

    this->matriculationNumber = matriculationNumber;
    this->semester            = semester;
}

Student::~Student()
{
    delete[] this->name;
    delete[] this->firstName;
}

std::ostream &operator<<(std::ostream &stream, const Student &input)
{
    stream << input.name << ", " << input.firstName << ": "
           << input.semester << " Semester, MA " << input.matriculationNumber;

    return stream;
}

和我的主要

#include <iostream>
#include "StudentPackage/Collection/StudentCollection.h"

int main()
{
    Student studentOne((char *)"Testerson", (char *)"Test", 12345, 2);
    std::cout << studentOne << std::endl;

    return 0;
}

我試過的

我已經嘗試了幾件事,包括 memcpy。 但是使用 memcpy 我無法正確檢測 char 數組的大小。

當我將學生構造函數更改為以下內容時,我遇到了析構函數中的刪除/釋放問題。 我想,這無論如何都不是正確的方法,但這正在發生,因為輸入變量的 scope 在調用 class 析構函數之前被破壞,對嗎?

Student::Student(char *name, char *firstName, unsigned matriculationNumber, unsigned semester)
{
    this->name      = name;
    this->firstName = firstName;

    this->matriculationNumber = matriculationNumber;
    this->semester            = semester;
}

問題

  1. 如何正確地從構造函數復制 char 數組(名稱到 this->name)?
  2. 我怎樣才能正確地從構造函數復制 char 數組(firstName 到 this->firstName)?

std::strcpy不分配 memory。 因此,您的程序將輸入復制到“垃圾”地址,該地址發生在放置Student object 的 memory 區域中。 結果,您會遇到段違規,這不足為奇。 有兩種解決方案:

  • 一種“C 風格”的方式 - 手動分配 memory(即像auto n = std::strlen(name); this->name = new char[n + 1]; std::strcpy(this->name, name); ),但是你需要在析構函數中手動刪除它(即delete name; )。 順便說一句, n + 1因為您還需要空終止符的空間, strlen結果不包括它。
  • 更好和更多的“C++”方式 - 使用std::string (即將name成員變量聲明為std::string )。 然后你就可以做一個分配: this->name = name; ,並且不需要手動 memory 管理 - std::string會照顧。
  • (代碼風格) 還建議對成員變量使用一些前綴或后綴,例如m_name (更“微軟”風格),或name_ - 更“谷歌”風格,以避免那些不必要的this->

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM