RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1056591
Accepted
Павел Ериков
Павел Ериков
Asked:2020-12-10 04:33:47 +0000 UTC2020-12-10 04:33:47 +0000 UTC 2020-12-10 04:33:47 +0000 UTC

C++中的回调函数

  • 772

我想确保我正确和充分地编写了所有内容。请告诉我代码中存在哪些错误,最好是关于如何正确处理的建议。

#include <iostream>
using namespace std;


class Point {
private:
    int xPos, yPos;
public:
    Point(int x, int y) : xPos(x), yPos(y) { }
    Point() : Point(0,0) { }
    int x() { return xPos; }
    int y() { return yPos; }
    void setX(int x) { this->xPos = x; }
    void setY(int y) { this->yPos = y; }
};

class Square {
private:
    void(*callBackFunc)(Point point);
    Point posLeftUp;
public:
    Square(){}
    Square(Point pos) : posLeftUp(pos) {}
    //Имитация движения квадрата по окну
    void Move(char key) {
        if (key == 'A')
            posLeftUp.setX(posLeftUp.x() - 2);
        else if (key == 'D')
            posLeftUp.setX(posLeftUp.x() + 2);
        else if (key == 'W')
            posLeftUp.setY(posLeftUp.y() + 2);
        else if (key == 'S')
            posLeftUp.setY(posLeftUp.y() - 2);
        callBackFunc(posLeftUp);
    }
    void setCallbackFunc(void(*fn)(Point point)) {
        callBackFunc = fn;
    }
};
//Имитация окна
class MainWindow {
private:
    static void getPosition(Point point);
    Square square;
public:
    MainWindow() {
        Point pos(10, 10);
        square = Square(pos);
        square.setCallbackFunc(getPosition);
        square.Move('A');
        square.Move('D');
        square.Move('W');
        square.Move('S');
    }
};

void MainWindow::getPosition(Point point){
        cout << point.x() << " : " << point.y() << endl;
}

int main() {
    MainWindow test;
    return 0;
}
c++
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    ВЛ 80
    2020-12-10T05:10:28Z2020-12-10T05:10:28Z

    以下是我可以评论的几点。

    在类定义中,我将首先指定public,因为这是类的接口。

    class Point {
    public:
        Point(int x, int y) : xPos(x), yPos(y) { }
        Point() : Point(0,0) { }
        int x() { return xPos; }
        int y() { return yPos; }
        void setX(int x) { xPos = x; }
        void setY(int y) { yPos = y; }
    private:
        int xPos;
        int yPos;
    };
    

    不要在一行上合并声明:

        // плохо:
        // int xPos, yPos; 
    
        // хорошо:
        int xPos;
        int yPos;
    

    在setX并且setY不使用this:

    void setX(int x) { xPos = x; }
    void setY(int y) { yPos = y; }
    

    switch中使用Move()。他非常适合这里。

    void Move(char key) {
        switch(key)
        {
        case 'A': posLeftUp.setX(posLeftUp.x() - 2); break;
        case 'D': posLeftUp.setX(posLeftUp.x() + 2); break;
        case 'W': posLeftUp.setY(posLeftUp.y() + 2); break;
        case 'S': posLeftUp.setY(posLeftUp.y() - 2); break;
        }
    
        callBackFunc(posLeftUp);
    }
    

    const在不应该改变的地方使用变量。编译器将帮助您避免愚蠢的错误:

    void Move(const char key) {
    

    在main()可以删除return 0;。当它main()到达结尾并且return丢失时,它将return 0;自动被暗示。


    正如@Andrey 所提到的,通过“将声明与类中的定义分开”,这意味着创建单独的文件来声明类和定义其方法。以你的为例class Square:

    让我们创建两个文件:square.hpp和square.cpp.

    square.hpp:

    #ifndef SQUARE_HPP
    #define SQUARE_HPP
    
    #include <functional>
    #include "Point.hpp"   // Файл, содержащий объявление класса Point
    
    class Square {
    public:
        Square();
        Square(const Point pos);
        void Move(const char key);
        void setCallbackFunc(std::function<void(const Point p)>);
    
    private:
        std::function<void(const Point p)> callBackFunc;
        Point posLeftUp;
    };
    
    #endif //SQUARE_HPP
    

    在这个文件中,我们声明了类Square,即我们列出了它的方法和成员。这足以知道如何在其他地方使用这个类。

    这种设计被称为 Header guard(“header guard” -所以它会是俄语?)

    #ifndef SQUARE_HPP
    #define SQUARE_HPP
    
    // ...
    
    #endif //SQUARE_HPP
    

    它可以防止该文件在编译期间多次hpp嵌套在同一个文件中。cpp

    这些方法如何实现的细节将放在第二个文件中

    square.cpp:

    #include "square.hpp"
    
    Square::Square() : callBackFunc(nullptr)
    {}
    
    Square::Square(const Point pos) :
        callBackFunc(nullptr),
        posLeftUp(pos)
    {}
    
    void Square::Move(const char key)
    {
        switch(key)
        {
        case 'A': posLeftUp.setX(posLeftUp.x() - 2); break;
        case 'D': posLeftUp.setX(posLeftUp.x() + 2); break;
        case 'W': posLeftUp.setY(posLeftUp.y() + 2); break;
        case 'S': posLeftUp.setY(posLeftUp.y() - 2); break;
        }
    
        if(callBackFunc)
        {
            callBackFunc(posLeftUp);
        }
    }
    
    void Square::setCallbackFunc(std::function<void(const Point p)> fn)
    {
        callBackFunc = fn;
    }
    

    因此,我们将类接口与其方法的实现分开。


    顺便说一句,一个类Point实际上可能只是一个结构,因为它的私有成员通过您定义的方法xPos是yPos完全可读和可写的。setX()并且setY()不做额外的工作,即隐藏为私人成员x也没有任何好处:y

    struct Point{
        Point() : x(0), y(0) {};
        Point(const int x, const int y) : x(x), y(y) {};
        int x;
        int y;
    };
    

    如果我们有义务检查传递的值,那是另一回事setX(),然后将其setY()隐藏为私有是合理的:xy

    void Point::setX(const int val)
    {
        constexpr int min_value = -100;
        constexpr int max_value = 100;
    
        if (val < min_value || val > max_value)
        {
            // Ошибка. Переданное значение неприемлемо.
            throw std::runtime_error("setX(): значение вне диапазона");
        }
    
        x = val;
    }
    

    关于回调。使用标题中的工具<functional>:

    std::function<>- 可以包含函数的包装类。

    std::bind()- 将一个函数的执行绑定到另一个函数的函数,向它传递可以预定义的参数。

    #include <functional>
    #include <iostream>
    using namespace std;
    
    
    class Point {
    public:
        Point(int x, int y) : xPos(x), yPos(y) { }
        Point() : Point(0,0) { }
        int x() { return xPos; }
        int y() { return yPos; }
        void setX(int x) { xPos = x; }
        void setY(int y) { yPos = y; }
    
    private:
        int xPos;
        int yPos;
    
    };
    
    class Square {
    public:
        Square(){}
        Square(Point pos) : posLeftUp(pos) {}
        //Имитация движения квадрата по окну
        void Move(const char key) {
            switch(key)
            {
            case 'A': posLeftUp.setX(posLeftUp.x() - 2); break;
            case 'D': posLeftUp.setX(posLeftUp.x() + 2); break;
            case 'W': posLeftUp.setY(posLeftUp.y() + 2); break;
            case 'S': posLeftUp.setY(posLeftUp.y() - 2); break;
            }
    
            if(callBackFunc)
            {
                callBackFunc(posLeftUp);
            }
        }
    
        void setCallbackFunc(std::function<void(const Point p)> fn) {
            callBackFunc = fn;
        }
    
    private:
        std::function<void(const Point p)> callBackFunc = nullptr;
        Point posLeftUp;
    };
    //Имитация окна
    class MainWindow {
    private:
        static void getPosition(Point point);
        Square square;
    public:
        MainWindow() {
            using namespace std::placeholders;
    
            Point pos(10, 10);
            square = Square(pos);
            square.setCallbackFunc(std::bind(&MainWindow::getPosition, _1));
            square.Move('A');
            square.Move('D');
            square.Move('W');
            square.Move('S');
        }
    };
    
    void MainWindow::getPosition(Point point){
            cout << point.x() << " : " << point.y() << endl;
    }
    
    int main() {
        MainWindow test;
    }
    
    • 4

相关问题

  • C++ 和循环依赖

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5