• 定义和实现模板类不能在同一个文件


            写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;
    };
    
    #endif
    stack.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
    ");
    	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
    ");
    	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
    ");
    	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
    ");
    	return m_Container.back();
    }
    
    #endif

    最后測试

    #include "stack_def.hpp"
    
    int main()
    {
    	CStack<int> IntStack;
    	IntStack.push(1);
    
    	system("pause");
    	return 0;
    }
    这样即可了!







    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    密码学
    MD5
    计算机基础之操作系统
    python中列表之间求差集、交集、并集
    Python语言中各种进制相互转换
    计算机基础
    bzoj2705 [SDOI2012]Longge的问题
    bzoj3160 万径人踪灭
    codeforces 528D Fuzzy Search
    杜教筛 && bzoj3944 Sum
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4667606.html
Copyright © 2020-2023  润新知