运算符“ =”未重载[关闭]

问题描述 投票:-4回答:1

我不知道为什么不能重载运算符“ =”,如下所示

    template<unsigned short maxsz>
    const natural<MAX_SIZE> &operator=(const natural<maxsz> &source) {

        setValue(source);
        return *this;
    }

其中natural是模板化的类natural \,用于其中具有大小和缓冲区的自然数。 setValue只是从源复制大小和缓冲区。该程序被编译并运行。但是重载的运算符不起作用。如果自然类没有模板,它将起作用。

下面是一个最小测试:

    #include <string.h>

    template<unsigned short MAX_SIZE>

    class natural {

    private:

        int size = 0;
        unsigned long long *binary = nullptr;

        void setValue(const unsigned long long *bin, int sz) {

            if (sz > 0) {

                if (binary)
                    delete[] binary;

                binary = new unsigned long long[sz];
                memcpy(binary, bin, sz * sizeof(unsigned long long));
                size = sz;
            }
        }

        template<unsigned short maxsz>
        void setValue(const natural<maxsz> &source) {

            setValue(source.binary, source.size);
        }

    public:

        natural() {}

        natural(const unsigned long long *buffer, int sz) {

            setValue(buffer, sz);
        }

        void testnatural() {

            size = 10;
            binary = new unsigned long long[size];

            for (int i = 0; i < 10; i++)
                binary[i] = i;
        }

        template<unsigned short maxsz>
        natural<MAX_SIZE> testfunction(const natural<maxsz> source) {

            natural<MAX_SIZE> result(source.binary, source.size);
            return result;
}

        template<unsigned short maxsz>
        const natural<MAX_SIZE> &operator=(const natural<maxsz> &source) {

           setValue(source);
        }

        ~natural() {

            if (binary)
                delete[] binary;
        }

    };

    int main() {

        natural<100> a, b, c;

        c.testnatural();

        a = b.testfunction(c);

        return 0;
    }

[运行程序时,出现错误:“ free():在tcache 2中检测到double free”。如果我删除析构函数中的内存释放,它会毫无错误地停止。现在,我不想在释放析构函数中的内存的同时消除此错误。

如果我没有记错的话,最后的分配不会调用我的重载运算符。请帮助我。

c++ overloading operator-keyword
1个回答
0
投票
谢谢您的答复。
© www.soinside.com 2019 - 2024. All rights reserved.