c++ - C++ 中的模板类和函数重载

标签 c++ class templates cout overloading

我正在练习在 C++ 中使用模板和类。我的目标是为双端队列编写一个模板类。它将具有“insert_head”、“insert_tail”、“remove_tail”和“remove head”的功能,以及使用“cout”打印的能力。此外,“=”运算符必须能够用于将类的一个实例复制到另一个实例。这是我当前的代码:

#ifndef DEQUE_H
#define DEQUE_H

template <typename T>
class Deque {
public:
    Deque(int size = 0, int capacity = 1000) : size_(size), capacity_(capacity) 
    {}
    Deque(Deque & d) : x_(d.x()), size_(d.size()), capacity_(d.capacity()) {}


std::ostream & operator<<(std::ostream & cout) {
    cout << '[';

    if (size_ > 0) {
        for (int i = 0; i < (size_ - 1)* sizeof(T); i += sizeof(T)) {
            std::cout << *(x_ + i) << ',';
        }
        cout << *(x_ + (size_ - 1)* sizeof(T));
    }
    cout << ']';
    return cout;
}

Deque operator=(Deque d) {
    Deque dq(d);
    return dq;
}

void print_test() {
    std::cout << '[';

    if (size_ > 0) {
        for (int i = 0; i < (size_ - 1)* sizeof(T); i += sizeof(T)) {
            std::cout << *(x_ + i) << ',';
        }
        std::cout << *(x_ + (size_ - 1)* sizeof(T));
    }
    std::cout << ']';
}

int * x() {
    return x_;
}
int size() {
    return size_;
}
int capacity() {
    return capacity_;
}

bool is_empty() {
    return size_ == 0;
}

void insert_tail(T tail) {
    if (size_ < capacity_) {
        *(x_ + sizeof(T) * size_) = tail;
        size_++;
    } else {
        // throw overflow
    }
}
T remove_tail() {
    if (size_ > 0) {
        T ret = *(x_ + sizeof(T) * (size_ - 1));
        std::cout << ret;
        size_--;
        return ret;
    } else {
        // throw underflow
    }
}

void insert_head(T head) {
    if (size_ > 0 && size_ < capacity_) {
        for (int i = (size_ - 1) * sizeof(T); i < 0; i -= sizeof(T)) {
            *(x_ + i + sizeof(T)) = *(x_ + i);
        }
    }
    if (size_ < capacity_) {
        *x_ = head;
        size_++;
    } else {
        // throw overflow
    }
}

T remove_head() {

    if (size_ > 0) {
        T ret = *x_;
        for (int i = sizeof(T); i < size_* sizeof(T); i += sizeof(T)) {
            *(x_ + i - sizeof(T)) = *(x_ + i);
        }   
        size_--;
        return ret;
    } else {
        // throw underflow
    }
}

private:
    T * x_;
    int size_;
    int capacity_;
};

#endif

这是我使用该类的测试代码:

#include <iostream>
#include "Deque.h"

int main(int argc, char const *argv[])
{
    Deque< int > dq;


    dq.insert_head(1);

    // dq.insert_head(2); // adding head when not empty causes bug

    dq.insert_tail(3);
    dq.insert_tail(4);
    dq.insert_tail(5);
    dq.print_test(); std::cout << std::endl;

    // std::cout << dq; // '<<' not overloaded properly'

    std::cout << dq.remove_head() << " head removed\n";

    // int x = dq.remove_head(); // seg faults when assigning returned value to a variable 

    dq.insert_tail(2);
    dq.print_test();
    std::cout << std::endl;

    Deque< int > dq1(dq);
    Deque< int > dq2;

    // dq2 = dq1; // '=' not overloaded properly

    return 0;
}

我的四个问题中的每一个都在我的测试文件中注释掉的代码行中,这里有进一步的解释:

  1. 当调用“dq.insert_head(2)”并且 dq 不为空(大小 > 0)时,我尝试将双端队列中的所有其他元素移动到一个位置,以便我可以在那里插入新值,有问题,元素没移过来。

  2. "std::cout << dq"没有按应有的方式打印 dq。该代码与“print_test()”方法非常相似,但是当我运行该程序时,出现错误“运算符 << 不匹配”。这是因为它是模板类吗?还是我在做其他完全错误的事情?

  3. 当尝试从双端队列中删除头或尾时,我试图返回删除的值。在未注释掉的代码行中,返回值按原样打印,但以下代码行导致段错误。是不是因为我试图将模板 varabale 分配给整数变量?

  4. 我的最后一个问题是“=”运算符没有将类的一个实例复制到另一个实例。我的目标是创建该类的一个新实例,然后返回该实例(如您在“Deque operator=(Deque d)”中看到的那样),但这并没有像我希望的那样工作。使用模板类重载“=”函数的最佳方法是什么。

感谢您的帮助,非常感谢您对这些问题的回答。

最佳答案

你所有的功能都有问题:

 Deque(int size = 0, int capacity = 1000) : size_(size), capacity_(capacity) {}
  • 如果允许指定大小,则必须为这些项目分配和初始化内存。您应该只指定容量。
  • x_ 未初始化。

假设,你想要一个固定的容量,那么你的构造函数应该是:

Deque(int capacity = 1000) 
    : size_(0)
    , x_(new T[capacity])
    , capacity_(capacity) 
{
}

即使那是一个简化版本,因为它会为所有可能效率低下并需要 T 的项目调用构造函数有一个可访问的默认构造函数。

现在是复制构造函数:

  • 拷贝构造函数应该进行深拷贝。否则,您的程序将(可能)在删除第一个 Deque 后崩溃。您已经完成复制,因为删除一个项目两次是未定义的行为。
  • 原型(prototype)应该采用常量引用,如:Deque(const Deque &other);

代码看起来类似于:

Deque(const Deque &other)
    : capacity_(other.capacity_)
    , x_(new T[other.capacity_])
    , size_(other.size_)
{
    for (int i = 0; i != size_; ++i)
    {
        x_[i] = other.x_[i];
    }
}

对于 << ,原型(prototype)应该是:

friend std::ostream & operator<<(std::ostream &cout, const T &data)

假设它在类内部声明为访问私有(private)字段。您需要传递运算符(operator)工作的数据。

对于赋值运算符,像这样的东西可以工作:

Deque& operator=(const Deque &other)
{
    // Use swap idiom...
    Deque tmp(other);

    // Swap pointers so old x_ get destroyed...
    T *old_x = x_;
    x_ = tmp.x_;
    tmp.x_ = old_x;

    // Usually one would use std::swap. 
    // Here as tmp get destroyed, it is not strictly to swap capacity_ and size_.
    capacity_ = tmp.capacity_;
    size_ = tmp.size_;
}

现在为 x()功能: - 如果你做一个队列,你可能不想公开数据所以这个功能应该被删除。 - 如果它被保留,函数应该是 const 并返回一个指向 T 的指针:T *x() const;对于预期的功能。

size , capacityis_empty应该都是const成员函数。

insert_tailremove_tail问题已在其他人的评论中得到解释(特别是无关的 sizeof )。

insert_head 的类似问题和 remove_head还。此外,复制现有项目的代码可以在私有(private)函数中重构,以遵循 DRY 原则并避免代码重复。

关于c++ - C++ 中的模板类和函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47763433/

相关文章:

c# - 访问 C# 类中的变量是否会从内存中读取整个类?

c# - 基类、派生类、Iclass?

c++ - 在类中重载运算符[],因此它可以从模板类中的数组返回对象

c++ - 模板化重载运算符的编译错误 "No global operator found"

c++ - 如何调试一个不那么熟悉的庞大代码库?

c++ - 我可以依靠TCHAR的定义对我使用的字符集做出正确的假设吗?

c++ - 仅修复 vector<vector<int>> 中的外部 vector

c++声明Rect结构与 union

c++ - 不同类如何操作一个函数一个

javascript - 无法调用未定义 Handlebars 问题的方法 'match'