这只是整个程序的一部分,在 Windows 中编译和运行良好,但它不喜欢我在 Linux/Unix 中的 strcpy。我做错了什么,我该如何解决?另外请注意,我不允许使用字符串,只能使用 cstring。
歌曲.cpp
#include "Song.h"
Song::Song()
{
}
Song::~Song()
{
}
Song::Song(char* title, char* artist, char* duration, char* album)
{
strcpy(this->title,50,title);
strcpy(this->artist, 50, artist);
strcpy(this->duration, 50, duration);
strcpy(this->album, 50, album);
}
void Song::setTitle(char* title)
{
this->title= title;
}
void Song::setArtist(char* artist)
{
this->artist = artist;
}
void Song::setDuration(char* duration)
{
this->duration= duration;
}
void Song::setAlbum(char* album)
{
this->album= album;
}
char* Song::getTitle()
{
return this->title;
}
char* Song::getArtist()
{
return this->artist;
}
char* Song::getDuration()
{
return this->duration;
}
char* Song::getAlbum()
{
return this->album;
}
宋.h
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <cctype>
using namespace std;
class Song
{
private:
char* title;
char* artist;
char* duration;
char* album;
public:
Song();
~Song();
Song(char* title, char* artist, char* duration, char* album);
void setTitle(char* title);
void setArtist(char* artist);
void setDuration(char* duration);
void setAlbum(char* album);
char* getTitle();
char* getArtist();
char* getDuration();
char* getAlbum();
};
最佳答案
您还没有为 strcpy
分配任何内存以复制到其中。因此,您的构造函数会调用未定义的行为。
你需要先分配一个字符数组。但是你还需要在你的每个 setter 中取消分配它。否则内存将泄漏,因为您正在重新分配管理它的指针。
关于c++ - 在 Linux/Unix 问题 C++ 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33489891/