C++ dynamic_cast 不是 return NULL

C++ dynamic_cast not return NULL

'File' 是我的基地 Class。导出目录。此函数写入目录 Class.

bool Directory::addParentPatch(File &otherFile)
{
   if(NULL==dynamic_cast<Directory*> (&otherFile))
   {   
       otherFile.addPath((*this).path());
       return true;
   }

   return false;
}

当我写主要的时候,那是行不通的。因为 dynamic_cast (&otherFile) 不是 return NULL。

int main
{
    Directory dir1;
    Directory dir2;
    TextFile text1;

    dir1.addParentPatch(text1); //I want this return true
    dir1.addParentPatch(dir2); //I want this return false

}

dir1.addParentPatch(text1)

dir1.addParentPatch(dir2)

在这两种情况下,return 都是正确的。但我不想要这个。如何解决?

您的代码按给定的方式运行,并添加了必要的粘合剂:

#include <iostream>

class File {
public:
    File() { }
    virtual ~File() { }
};

class Directory : public File {
public:
    Directory() { }
    bool addParentPatch (File &otherFile);
};

class TextFile : public File {
public:
    TextFile() { }
};

bool Directory::addParentPatch(File &otherFile)
{
   if(NULL==dynamic_cast<Directory*> (&otherFile))
       return true;

   return false;
}

int main ()
{
    Directory dir1;
    Directory dir2;
    TextFile text1;

    std::cout << dir1.addParentPatch(text1) << std::endl; //I want this return true
    std::cout << dir1.addParentPatch(dir2) << std::endl; //I want this return false
}

输出为

1
0

所以你可能弄乱了一些胶水。