gpt4 book ai didi

c++ - 使用 C++ 模板时对复制构造函数的 undefined reference

转载 作者:行者123 更新时间:2023-11-28 07:51:13 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why can templates only be implemented in the header file?

我正在尝试练习 C++ 模板,在练习时,g++ 给了我以下链接器错误:

g++ main.o list.o -o app
main.o: In function `main':
main.cpp:(.text+0x27): undefined reference to `List<int>::List(List<int> const&)'
collect2: ld returned 1 exit status
make: *** [app] Error 1

我尝试在我的 main 中执行以下操作:

#include "List.h"

int main() {
List<int> a;
List<int> b(a);
return 0;
}

虽然我的 List.h 看起来像:

#ifndef LST_H
#define LST_H

template <typename T>
class List {
public:
template <typename TT> class Node;
private:
Node<T> *head;
public:
List() { head = new Node<T>; }
~List() { delete head; }
List( const List &l );

template <bool DIM> class iterable_frame;
template <bool DIM> class supervised_frame {
iterable_frame<DIM> sentinels;
iterable_frame<DIM> data;
bool sentinel_completeness;

public:
supervised_frame( const List& );
~supervised_frame() {}
void copy_sentinels( iterable_frame<DIM>& );
void copy_cells( iterable_frame<DIM>& );
};
template <bool DIM> class iterable_frame {
Node<T> *head;
Node<T> *caret;

public:
iterable_frame( const List& );
~iterable_frame() {}
inline bool end() { return head == caret; }
};
template <typename TT> class Node {
unsigned index[2];
TT num;
Node<TT> *next[2];
public:
Node( unsigned x = 0, unsigned y = 0 ) { index[0]=x; index[1]=y; next[0] = this; next[1] = this; }
Node( unsigned x, unsigned y, TT d ) { index[0]=x; index[1]=y; num=d; next[0] = this; next[1] = this; }
~Node() {}
friend class List;
};
};

#endif

和我的 List.cpp 一样:

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

template <typename T>
List<T>::List( const List<T> &l ) {
head = new Node<T>;
iterable_frame<1> in(l);
supervised_frame<1> out(*this);
}

template <typename T> template <bool DIM>
List<T>::supervised_frame<DIM>::supervised_frame( const List<T> &l ) {
std::cout << DIM << std::endl;
}
template <typename T> template <bool DIM>
void List<T>::supervised_frame<DIM>::copy_sentinels( iterable_frame<DIM>& ) {}
template <typename T> template <bool DIM>
void List<T>::supervised_frame<DIM>::copy_cells( iterable_frame<DIM>& ) {}

template <typename T> template <bool DIM>
List<T>::iterable_frame<DIM>::iterable_frame( const List<T> &l ) {
std::cout << '\t' << DIM << std::endl;
}

代码仍然是草稿,但我会稍微解释一下我的意图。背后的想法是我想要一个可以充当稀疏矩阵的类列表,所以我制作了第一个模板来轻松地在存储的数字类型(int、float 等)之间切换。然后我创建了两个类似迭代器的辅助类来处理元素,它们也是由模板实现的,因为迭代的方向可以是双重的——按列或按行,不同的矩阵方法会选择最适合它们的方法.列表是一个二维环。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com