写c++程序时我们经常会把函数的定义写在xxx.h中,把函数的实现写在xxx.cpp, 但是当我们写带模版的函数和类时,这样写
就会出现问题,如下:
stack.h
//stack.h #ifndef STACK_HPP #define STACK_HPP #include <vector> #include <stdexcept> template<typename T, typename TContainer = std::vector<T>> class CStack { public: void push(const T& vValue); void pop(); T top() const; bool empty() const {return m_Container.empty();} private: TContainer m_Container; }; #endifstack.cpp
#include "stack.h" template<typename T, typename TContainer> void CStack<T, TContainer>::push(const T& vValue) { m_Container.push_back(vValue); } template<typename T, typename TContainer> void CStack<T, TContainer>::pop() { if (empty()) throw std::out_of_range("Stack::pop: empty stack\n"); m_Container.pop_back(); } template<typename T, typename TContainer> T CStack<T, TContainer>::top() const { if (empty()) throw std::out_of_range("Stack::top: empty Stack\n"); return m_Container.back(); }然后在main函数中测试就会出错:
#include "stack.h" int main() { stack<int> IntStack; .... }
首先定义 stack.hpp,类的定义
#ifndef STACK_HPP #define STACK_HPP #include <vector> #include <stdexcept> template<typename T, typename TContainer = std::vector<T>> class CStack { public: void push(const T& vValue); void pop(); T top() const; bool empty() const {return m_Container.empty();} private: TContainer m_Container; }; #endif然后定义stackdef.hpp 来实现模版中定义的函数
#ifndef STACKDEF_HPP #define STACKDEF_HPP #include "stack.hpp" template<typename T, typename TContainer> void CStack<T, TContainer>::push(const T& vValue) { m_Container.push_back(vValue); } template<typename T, typename TContainer> void CStack<T, TContainer>::pop() { if (empty()) throw std::out_of_range("Stack::pop: empty stack\n"); m_Container.pop_back(); } template<typename T, typename TContainer> T CStack<T, TContainer>::top() const { if (empty()) throw std::out_of_range("Stack::top: empty Stack\n"); return m_Container.back(); } #endif
最后测试
#include "stack_def.hpp" int main() { CStack<int> IntStack; IntStack.push(1); system("pause"); return 0; }这样就行了!
模板类的定义和实现可以不在同一个文件中,布布扣,bubuko.com
原文地址:http://blog.csdn.net/xiaoliangsky/article/details/37740159