C++赋值运算符重载

标签 c++ arrays templates variable-assignment operator-keyword

大家好,我正在尝试为此类编写赋值运算符,以便我可以将这样的数组int[] = {0, 1, 2, 3} 分配给我的 Tableau 类

本来我是想做这个的

Tableau<T>& operator=(T arr[])
{
 return Tableau(tab, sizeofarray);
}

因为我已经写了一个以数组和大小作为参数的构造函数

我遇到了数组大小的问题,我不知道如何找到它 我怎样才能找到数组的大小或者有更好的方法来做到这一点

template<typename T>
class Tableau
{ 
public:
Tableau(int s = 0) : size(s), ptr(new T[size])
{
    for (int i = 0; i < size; i++)
    {
        ptr[i] = 0;
    }
}
Tableau(T tab[], int s = 0) : size(s), ptr(new T[size])
{
    for (int i = 0; i < size; i++)
    {
        ptr[i] = tab[i];
    }
}

~Tableau()
{
    delete[] ptr;
}
Tableau<T>& operator=( T tab[])
{

}
T commule()
{
    T com = 0;
    for (int i = 0; i < size; i++)
    {
        com += ptr[i];
    }
    return com;
}
T& operator[](const int index)
{
    return ptr[index];
}
private:
int size;
T* ptr;
};

int main()
{
int k[] = { 8, 12, 5, 9, 55};
Tableau<int> TI(k, 2);
TI = k;
return 0;
}

最佳答案

您可以使用:

template <std::size_t N>
Tableau<T>& operator=(T (&arr)[N])
{
    // This is not right.
    // The returned value is a temporary.
    // return Tableau(arr, N);

    // Update the contents of the object.

    // ...

    // Then, return a reference to this object.
    return *this;
}

使用该成员函数模板,当您调用时:

int k[] = { 8, 12, 5, 9, 55};
Tableau<int> TI(k, 2);
TI = k;

operator= 函数是用 N = 5k 作为 arr 的值实例化的。因此,您可以获得数组的大小以及数组的内容。

但是,值得指出的是,如果您使用:

int k[] = { 8, 12, 5, 9, 55};
int* k2 = k;
Tableau<int> TI(k, 2);
TI = k2;

那是行不通的。 k2 不是数组。它是一个指向 int 的指针,它恰好指向 k 的第一个元素。

关于C++赋值运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37037926/

相关文章:

arrays - 如何创建扩展以允许自定义类型的数组符合协议(protocol)?

c++ - 如何在 C++ 中使用模板制作通用 map

javascript - Underscore.js 模板 : Template variable not rendered

node.js - 邮戳模板 : dynamic variable with html processed as text instead of html

c++ - 如何将 gdb 用于多线程网络程序

c++ - 无法找出将信号从 qml 绑定(bind)到 cpp 插槽的正确方法

c++ - 如何比较任意基数的数字

C从带有科学记数法的文件中读取输入到二维数组中

具有重叠矩形的 C++ 碰撞检测

php - 如何组合从下拉列表中选择的日期/时间以在 MySQL 查询中使用?