gpt4 book ai didi

c++ - dynamic_cast 的问题

转载 作者:行者123 更新时间:2023-11-30 02:11:40 30 4
gpt4 key购买 nike

我有这段代码:

void addLineRelative(LineNumber number, LineNumber relativeNumber) {
list<shared_ptr<Line> >::iterator i;
findLine(i, number);
if(i == listOfLines.end()){
throw "LineDoesNotExist";
}

line 15 if(dynamic_cast<shared_ptr<FamilyLine> >(*i)){
cout << "Family Line";
} else {
throw "Not A Family Line";
}
}

我有类 Line 并从它派生 FamilyLine 和 RegularLine,所以我想找到 FamilyLine

我的程序在第 15 行失败,我收到一个错误

cannot dynamic_cast target is not pointer or reference

有人可以帮忙吗,在此先感谢

已编辑

我试过这个:

shared_ptr<FamilyLine> ptr(dynamic_cast<shared_ptr<FamilyLine> >(*i));
if(ptr){
//do stuff
}

同样的错误

已编辑

void addLineRelative(LineNumber number, LineNumber relativeNumber) {
list<shared_ptr<Line> >::iterator i;
findLine(i, number);
if(i == listOfLines.end()){
throw "LineDoesNotExist";
}

shared_ptr<FamilyLine> ptr(dynamic_pointer_cast<FamilyLine>(*i));
if (ptr){
cout << "Family Line";
} else {
throw "Not A Family Line";
}
}

收到这个错误

Multiple markers at this line
- `dynamic_pointer_cast' was not declared in this
scope
- unused variable 'dynamic_pointer_cast'
- expected primary-expression before '>' token

最佳答案

shared_ptr不会隐式转换为指针 - 它是一个类类型对象 - 并且 dynamic_cast , static_castconst_cast都只对指针进行操作。

虽然您可以使用 dynamic_castshared_ptr<T>::get() ,最好用dynamic_pointer_cast<FamilyLine>()相反,否则您可能会不小心引入双 delete小号:

Returns:
* When dynamic_cast<T*>(r.get()) returns a nonzero value, a shared_ptr<T> object that stores a copy of it and shares ownership with r;
* Otherwise, an empty shared_ptr<T> object.
[...]
Notes: the seemingly equivalent expression

shared_ptr<T>(dynamic_cast<T*>(r.get()))

will eventually result in undefined behavior, attempting to delete the same object twice.

例如:

shared_ptr<FamilyLine> ptr(dynamic_pointer_cast<FamilyLine>(*i));
if (ptr) {
// ... do stuff with ptr
}

关于c++ - dynamic_cast 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3076243/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com