说,我想创建一个File类
class File{
public:
File(const char *file){
openFile(file);
}
~File();
isEmpty();
};
Run Code Online (Sandbox Code Playgroud)
openFile检查文件是否存在或文件内容是否有效.
File *file = new File("filepath");
if(file)
file->isEmpty();
Run Code Online (Sandbox Code Playgroud)
如果我的文件路径是正确的,那么所有正常的文件实例都是正确的,我们可以调用file->isEmpty();
该文件不存在的内容,在这种情况下,检查结果仍为if(file)true,并将导致创建实际上无效的文件实例.如何保证如果文件路径无效,则文件实例应为null.
在无法打开文件的情况下,构造函数应抛出异常.
File::File( const char* pPath )
{
if ( !openFile( pPath ) )
throw FileNotFound( pPath );
}
Run Code Online (Sandbox Code Playgroud)