Dynamic_cast 给出分段错误

问题描述

我知道虚函数和多态是什么。我在理解下面的代码时有点困惑。

class book //your custom class
{
private:
    string author;
    int pages;
public: 
    book(const string &str,int num): author(str),pages(num) {} 
    friend bool pages_compare(const book& lhs,const book& rhs); //friend comparator. If your fields are public,you may remove "friendship"
    friend bool author_compare(const book& lhs,const book& rhs);//friend comparator. If your fields are public,you may remove "friendship"
    friend void print(const book& arg);
};

bool pages_compare(const book& lhs,const book& rhs) // func for sorting by pages count
{
    return lhs.pages < rhs.pages;
}

bool author_compare(const book& lhs,const book& rhs) // func for sorting by author name
{
    return lhs.author < rhs.author;
}

void print(const book& arg) // custom printing
{
    cout << '{' << arg.author << "," << arg.pages << "} ";
}

int main()
{
    book book0{"aurelius",10};
    book book1{"bbbbbb",5};
    book book2{"ccccc",15};
    book book3{"au",100};
    vector<book> arr = {book0,book1,book2,book3};
    sort(arr.begin(),arr.end(),pages_compare); // sort by page count
    for(auto &i: arr) // print
        print(i); // {bbbbbb,5} {aurelius,10} {ccccc,15} {au,100} 
    cout << '\n';
    sort(arr.begin(),author_compare); // sort by author name
    for(auto &i: arr) // print
        print(i); // {au,100} {aurelius,10} {bbbbbb,5} {ccccc,15} 
}

我不确定为什么在基类上使用 dynamic_cast 会导致分段错误。我应该期望输出“派生显示”作为输出。有人可以给我任何线索和更好的解释。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)