c++ - 模板的复制构造函数

标签 c++ templates g++ copy-constructor

复制构造函数在以下代码中失败。为了清楚起见,我已经剪掉了代码

#include <iostream>
#include <stdio.h>
#include <assert.h>

namespace my {
    template <class T>
    class Sptr {
    private:
        //some kind of pointer
            //one to current obj
        T* obj;
.
.
.
    public:
.
.
.

        Sptr(const Sptr &);

        template <typename U> 
        Sptr(const Sptr<U> &);

.
.
.
};//Class ends

    template <typename T>
    template <typename U> 
    Sptr<T>::Sptr(U* u) {
        //do something
    }

    template <typename T>
    Sptr<T>::Sptr(const Sptr<T> &copyObj) {
        //do copy constructor stuff
    }
.
.
.
}

using namespace std;
using namespace my;
/* Basic Tests 1 ================================================================================ */
size_t AllocatedSpace;

class Base1 {
    protected:
        Base1() : derived_destructor_called(false) {
            printf("Base1::Base1()\n");
        }
    private:
        Base1(const Base1 &); // Disallow.
        Base1 &operator=(const Base1 &); // Disallow.
    public:
        virtual ~Base1() {
            printf("Base1::~Base1()\n");
            assert(derived_destructor_called);
        }
    protected:
        bool derived_destructor_called;
};

class Derived : public Base1 {
        friend void basic_tests_1();
    private:
        Derived() {}
        Derived(const Derived &); // Disallow.
        Derived &operator=(const Derived &); // Disallow.
    public:
        ~Derived() {
            printf("Derived::~Derived()\n");
            derived_destructor_called = true;
        }
        int value;
};

此测试代码行产生错误 Sptr<Base1> sp3(sp);

void basic_tests_1() {


    //size_t base = AllocatedSpace;

    // Test deleting through original class.
    {
        // Base1 assigned from Sptr<Derived>.
        {
            Sptr<Base1> sp2;
            {
                Sptr<Derived> sp(new Derived);
                // Test template copy constructor.
                Sptr<Base1> sp3(sp);
                sp2 = sp;
                sp2 = sp2;
            }
        }
    }
}

错误:

/tmp/ccKrn1xG.o: In function `basic_tests_1()':
Sptr.cpp:(.text+0x81): undefined reference to `my::Sptr<Base1>::Sptr<Derived>(my::Sptr<Derived> const&)'
collect2: error: ld returned 1 exit status

最佳答案

你已经在类中声明了这个构造函数:

    template <typename U> 
    Sptr(const Sptr<U> &);

但是你还没有给出定义。错误消息说您从未定义它。我的猜测是错误信息是正确的。尝试解决这个问题。

关于c++ - 模板的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733288/

相关文章:

C++ - 试图重载 "<<"运算符

c++ - 在方法声明中使用 typedef 但在方法定义中使用规范类型是否合法 C++?

c++正确关闭cout

c++ - BlockingQueue 的 QWaitCondition : Destroyed while threads are still waiting

c++ - 指向模板类作为该类参数的指针

c++ - 程序总是产生相同的值(value)?

C++17 std::G++ 中的可选?

c++ - C++ 中的多数函数使用 3 uint8_t

C++ 函数重载和 initializer_list 构造函数

php - WooCommerce 中生成的项目(产品)表在哪里