设为首页 加入收藏

TOP

模板类的定义和实现可以不在同一个文件中
2015-07-20 18:07:46 来源: 作者: 【 】 浏览:5
Tags:模板 义和 实现 可以 不在 同一个 文件

写c++程序时我们经常会把函数的定义写在xxx.h中,把函数的实现写在xxx.cpp, 但是当我们写带模版的函数和类时,这样写

就会出现问题,如下:

stack.h

//stack.h
#ifndef STACK_HPP
#define STACK_HPP

#include 
  
   
#include 
   
     template
    
     > 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
    
   
  
stack.cpp

#include "stack.h"
template
  
   
void CStack
   
    ::push(const T& vValue) { m_Container.push_back(vValue); } template
    
      void CStack
     
      ::pop() { if (empty()) throw std::out_of_range("Stack::pop: empty stack\n"); m_Container.pop_back(); } template
      
        T CStack
       
        ::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
  
    IntStack;
       ....
}
  


以前总是没办法,只能把定义和实现写在同一个文件中,今天终于找到一种解决方法

首先定义 stack.hpp,类的定义

#ifndef STACK_HPP
#define STACK_HPP

#include 
  
   
#include 
   
     template
    
     > 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
  
   
void CStack
   
    ::push(const T& vValue) { m_Container.push_back(vValue); } template
    
      void CStack
     
      ::pop() { if (empty()) throw std::out_of_range("Stack::pop: empty stack\n"); m_Container.pop_back(); } template
      
        T CStack
       
        ::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
  
    IntStack;
	IntStack.push(1);

	system("pause");
	return 0;
}
  
这样就行了!







】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇(素数求解)I - Dirichlet's.. 下一篇HDU 1051 Wooden Sticks (贪心)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: