我需要定义一个强制转换构造函数—一个表示文档名称的参数



如果不是很难,请告诉我-我有一个"文档";类,包含以下字段:

char * name 
char * subject
char * author
int page
int date
int time

在这个类中,我需要定义一个类型转换构造函数——一个表示文档名称的参数。

  1. 我的构造函数应该接受一个字符串对象并将其转换为一个赋能数组吗?

  2. 我做的对吗?


Document::Document( const string str ) { ctor type casting - accept an object of type string (document name)
name = new char[ str.length() + 1 ];  // then using c_str - returns an array of char type, terminated with zero
strcpy ( name , str.c_str() );       // After converting string to char - write it in the "name" field of the Document class
topic   = new char[1];               // For the rest of the char fields - allocate one byte of memory
author  = new char[1];
pages   = date = time = 0;            // Fields of type int - initialized with zeros
} 

Q:我的构造函数是否应该接受一个字符串对象并将其转换为一个字符数组(假设enchanted数组实际上是一个char数组)?

:你的代码看起来或多或少是正确的,尽管你可能不应该在你的类中使用字符数组,而只是有std::string。这会省去你很多麻烦。

问:我做的对吗?

:是或否,你展示的代码或多或少是正确的,但使用char数组而不是std::strings的一般方法在我看来是错误的。

它会简单地这样做:

class Document
{
std::string name;
std::string subject;
std::string author;
int pages;
int date;
int time;
public:
Document(const std::string & str);
};
Document::Document(const std::string & str)
{
name = str;
pages = date = time = 0;
}

或更好:

class Document
{
std::string name;
std::string subject;
std::string author;
int pages = 0;
int date = 0;
int time = 0;
public:
Document(const std::string & str);
};
Document::Document(const std::string & str)
: name(str)
{
}

用法示例:

int main()
{
Document foo("bar");
...
}

最新更新