c++ 模版的一些注意问题

声明和定义不可分离

举个例子:
定义一个Stack.h: 这里放声明

#include

using namespace std;

template<class T>
T Add(const T& left, const T& right);

定义一个Stack.cpp, 这里面放定义:

template<class T>
T Add(const T& left, const T& right)
{
	cout << " T Add(const T& left, const T& right) " << endl;
	return left + right;
}

再来一个用来使用上述函数的Test.cpp:

#include"Stack.h"

int main()
{
	Add(1, 2);
	return 0;
}

当你运行上面的代码之后为发生报错:
在这里插入图片描述
这是一个链接报错

为什么?
因为上面的Add 函数不是一个普通函数 而是 一个函数模版
为了理解这个原因,我们首先需要知道下面的步骤:
c++ 模版的一些注意问题_第1张图片
所以当你按下 fn + f5 之后上面的代码是这样的:

c++ 模版的一些注意问题_第2张图片

‍♂️那我们如何解决呢?
1 显示实例化
Stack.cpp 中 我们不是没有实例化导致没法生成地址吗,那我们就实例化它,我们在stack.cpp 中加入

template
int Add<int>(const int& left, const int& right);

这样就行了,我们把它实例化为了int, 但是这样有个弊端,我想用double类型怎么办? 所以这也不是万全之策;

  1. 万全之策
    你就不要把声明和定义分开写嘛,你就把Stack.cpp 移除了 把声明和定义他们两个写到同一个文件:Stack.h中;
#pragma once
 
#include

using namespace std;

template<class T>
T Add(const T& left, const T& right);

template<class T>
class Stack
{
public:
	void Push(const T& x);
	void Pop();

private:
	T* _a = nullptr;
	int _top = 0;
	int _capacity = 0;
};



template<class T>
T Add(const T& left, const T& right)
{
	cout << " T Add(const T& left, const T& right) " << endl;
	return left + right;
}


template<class T>
void Stack<T>::Push(const T& x)
{
	cout << "void Stack::Push(const T& x)" << endl;
}


template<class T>
void Stack<T>::Pop()
{
	cout << "void Stack::Push()" << endl;
}


你可能感兴趣的:(c++)