'文件'是我的基类。目录是派生的。此函数在Directory Class中编写。
bool Directory::addParentPatch(File &otherFile)
{
if(NULL==dynamic_cast<Directory*> (&otherFile))
{
otherFile.addPath((*this).path());
return true;
}
return false;
}
当我写主要内容时,这不起作用。因为dynamic_cast(&amp; otherFile)不返回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(文本1)
dir1.addParentPatch(DIR2)
在这两种情况下,都返回true。但我不想要这个。如何解决?
答案 0 :(得分:0)
您的代码按照给定的方式工作,并添加了必要的胶水:
#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
所以你可能搞砸了一些胶水。