使用dynamic_cast转换有关问题
使用dynamic_cast转换问题!帮忙看看是什么问题:C/C++ code#include iostream#include fstream#include
使用dynamic_cast转换问题!
帮忙看看是什么问题:
C/C++ code#include <iostream>#include <fstream>#include <string>using namespace std;void write(ostream &file){ ofstream &file1=dynamic_cast<ofstream&>(file); file1.put('a');}int main(){ string filename; cin>>filename; ofstream ifile; ifile.open(filename.c_str(),ofstream::app); write(ifile); ifile.close(); ifile.clear(); return 0; }
[解决办法]当然不对了
dynamic_cast是向上转化的,你这是向下转换,不安全
[解决办法]MSDN
class B { ... };
class D : public B { ... };
void f()
{
B* pb = new D; // unclear but ok
B* pb2 = new B;
D* pd = dynamic_cast<D*>(pb); // ok: pb actually points to a D
...
D* pd2 = dynamic_cast<D*>(pb2); //error: pb2 points to a B, not a D
// pd2 == NULL
...
}