polymorphic read

#quote from MIT 'introduction to computation and programming using python, Revised' 
def readVal(valType, requestMsg, errorMsg):
    while True:
        val = raw_input(requestMsg + ' ')
        try:
            val = valType(val)
            return val
        except ValueError:
            print val, errorMsg
            
n = readVal(int, 'Enter an integer:', 'is not an integer.')
print n
%run "C:\Users\Administrator\test.py"


Enter an integer: hello
hello is not an integer.


Enter an integer: 12.99
12.99 is not an integer.


Enter an integer: 34
34


在 C++ 中,source type is not polymorphic 是一个编译错误,表示源类型不是多态类型。多态类型是指至少包含一个虚函数的类型,通过基类指针或引用可以访问其派生类对象的成员函数。如果源类型不是多态类型,那么无法使用 dynamic_cast 将其指针或引用转换为派生类指针或引用。 例如,下面的代码会出现 source type is not polymorphic 错误: ``` class Base { public: void func() { cout << "This is Base class" << endl; } }; class Sub : public Base { public: void sub_func() { cout << "This is Sub class special function" << endl; } }; int main() { Base base_obj; Sub *sub_ptr = dynamic_cast<Sub*>(&base_obj); // 错误:source type is not polymorphic return 0; } ``` 因为 Base 类中没有虚函数,所以 Base 类不是多态类型,无法进行 dynamic_cast 转换。解决该错误的方法是在 Base 类中添加虚函数,将其变成多态类型。例如: ``` class Base { public: virtual void func() { cout << "This is Base class" << endl; } }; class Sub : public Base { public: void sub_func() { cout << "This is Sub class special function" << endl; } }; int main() { Sub sub_obj; Base *base_ptr = &sub_obj; Sub *sub_ptr = dynamic_cast<Sub*>(base_ptr); // 正确:进行子类向下转型 if (sub_ptr != nullptr) { sub_ptr->sub_func(); // 输出:This is Sub class special function } return 0; } ``` 在 Base 类中添加了虚函数 func,将其变成多态类型,可以正确进行 dynamic_cast 转换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值