赞
踩
示例代码如下:
#include <iostream> using namespace std; class Shape { protected: int width, height; public: virtual int area() = 0; // 纯虚函数 void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } }; class Rectangle: public Shape { public: int area() { return width * height; } }; class Triangle: public Shape { public: int area() { return (width * height) / 2; } }; int main() { Rectangle rect; Triangle tri; rect.setWidth(5); rect.setHeight(7); cout << "矩形的面积:" << rect.area() << endl; tri.setWidth(5); tri.setHeight(7); cout << "三角形的面积:" << tri.area() << endl; return 0; }
在上面的示例中,Shape是一个抽象类,它有一个纯虚函数area()。Rectangle和Triangle是Shape的派生类,它们必须实现纯虚函数area()。在main函数中,我们创建了Rectangle和Triangle的对象,并调用它们的area()函数来计算面积。
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); Obj = new BClass(); QObject::connect(Obj, &AClass::signalPureVirtualFunction, [&]() { std::cout << "in 1" << std::endl; }); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { Obj->pureVirtualFunction(); }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <iostream> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class AClass : public QObject { Q_OBJECT public: virtual void pureVirtualFunction() = 0; signals: void signalPureVirtualFunction(); }; class BClass : public AClass { Q_OBJECT public: void pureVirtualFunction() override { std::cout << "send" << std::endl; emit signalPureVirtualFunction(); } }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_clicked(); private: Ui::MainWindow *ui; AClass *Obj; }; #endif // MAINWINDOW_H
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。