Qt|C++工作笔记-对虚函数的进一步认识(关键是Qt中如何正确使用,达到想要的效果)
程序员文章站
2022-07-13 22:02:15
...
关于虚函数的简单例子
首先是一个很简单例子,刚学C++的朋友都能理解
源码如下:
#include <cstdio>
#include <windows.h>
static int criticalRes = 1; //critical resource
class Base {
public:
virtual void print() {
printf("print called in Base Class!\n");
//critical resource will be modified by Base Class
criticalRes *= 1000;
}
};
class Child:public Base {
public:
virtual void print() { // "virtual" can be removed or reserve
printf("print called in Child Class!\n");
criticalRes -= 1;
Base::print();
printf("The criticalRes's value is %d\n", criticalRes);
}
};
void main() {
Child *child = new Child;
child->print();
delete child;
getchar();
}
运行截图如下:
程序逻辑:先把临界资源的值减少了1,再调用父类的函数,乘1000。
把代码改下:
#include <cstdio>
#include <windows.h>
static int criticalRes = 1; //critical resource
class Base {
public:
virtual void print() {
printf("print called in Base Class!\n");
//critical resource will be modified by Base Class
criticalRes *= 1000;
}
};
class Child:public Base {
public:
virtual void print() { // "virtual" can be removed or reserve
Base::print();
printf("print called in Child Class!\n");
criticalRes -= 1;
printf("The criticalRes's value is %d\n", criticalRes);
}
};
void main() {
Child *child = new Child;
child->print();
delete child;
getchar();
}
运行截图如下:
程序运行逻辑:先调用父类把临界资源的指乘了1000,再减少了1。
在Qt中应该注意的问题
上面那个只是小小的知识点,在Qt中,要利用这个特性,完成我们想要达到的功能。
比如上次说的三只小猪的例子【链接如下:https://blog.csdn.net/qq78442761/article/details/82182054】
给出鼠标单击时候的代码:
void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(index.data().canConvert<MyPic>()){
//qDebug()<<"can be convert!";
MyPic mypic=qvariant_cast<MyPic>(index.data());
mypic.paint(painter,option.rect,option.palette);
}
else{
qDebug()<<"can't be convert!";
}
QStyledItemDelegate::paint(painter, option, index);
}
运行截图如下:
这种运行太令人糟糕了,我们不要他被覆盖掉!
改成如下的代码:
void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyledItemDelegate::paint(painter, option, index);
if(index.data().canConvert<MyPic>()){
//qDebug()<<"can be convert!";
MyPic mypic=qvariant_cast<MyPic>(index.data());
mypic.paint(painter,option.rect,option.palette);
}
else{
qDebug()<<"can't be convert!";
}
}
运行截图如下: