c++ - 标准矩形类

标签 c++

我有一个项目,它有一个 GUI(用 QT 编写)和一个命令行版本。我使用了 QT 中包含的矩形类:QRect .我想打破命令行版本对 QT 的依赖,所以我需要一个支持交集和 union 的插入式矩形类。我可以写一个,但如果可能的话我更愿意包括一个。

有什么想法吗?

最佳答案

如果您要找到一个要包含的内容,它可能是另一个依赖项的一部分。所以你最好的选择是尝试编写你自己的。现在是练习制作模板类的好时机。 :)

template <typename T>
struct point
{
    // or maybe you'd prefer to make these private
    T x;
    T y;
};

template <typename T>
struct rectangle
{
public:
    typedef point<T> point_type;

    bool contains(const point_type& pPoint)
    {
        return !(pPoint.x < topleft.x) && (pPoint.x < bottomright.x) && 
                !(pPoint.y < topleft.y) && (pPoint.y < bottomright.y);
    }

    T width(void) const
    {
        return bottomright.x - topleft.x;
    }

    // and more stuff

    // or maybe you'd prefer to make these private, nor
    // is this the only way to represent a rectangle.
    point_type topleft;
    point_type bottomright;
};

抱歉,这不是您期待的答案。


就您的设计而言,我希望您不会采用您的 GUI 版本,执行复制,然后将其修改为控制台版本。最好是建立一个图书馆;那么 GUI 与控制台只是一个演示问题。

关于c++ - 标准矩形类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2641855/

相关文章:

c++ - 为什么我可以使用 make_unique 创建带有衰减数组指针的 unique_ptr?

c++ - 如何避免辅助函数被警告? "xxx defined but not used"

c++ - 如何知道在C++中抛出异常的原因

c++ - 在 C++11 中序列化类型 id?

c++ - 在 GTK 中保存/恢复窗口位置

c++ - 构造函数/析构函数是否必须有代码,或者函数是否足够?

C++ Processentry32

C++访问另一个类的数据成员

c++ - 为什么 setjmp/longjmp 的这种用法是未定义的行为?

c++ - 将 float 转换为 LPCWSTR