C++ include的一些问题

1. 如果在C++里面要定义类模板,

举个例子:

stack.h

enum Error_code{underflow,overflow,success};
const int maxstack = 1000;

template
class Stack{
public:
    Stack();
    bool empty() const;
    Error_code pop();
    Error_code top(Stack_entry & item) const;
    Error_code push(const Stack_entry &item);
private:
    int count;
    Stack_entry entry[maxstack];
};

stack.cpp

#include "stack.h"


template
Stack::Stack(){
    // 类的不带参数的默认构造函数。一开始把栈里面的个数设置成0
    count = 0;
}

template
bool Stack::empty() const{
    // 后态:如果Stack非空,那么返回false。
    // 否则的话返回true。
    return count==0;
}

template
Error_code Stack::pop() {
// 后态: 如果栈是空的返回Error_code里面的underflow
//        否则的话,将栈的count减一,并且返回success的
//        Error_code
    Error_code outcome = success;
    // 这样写可以指明success是一个Error_code的类型
    // 这样方便我们后面的检查。
    if(count<=0) {
        outcome = underflow;
    } else count--;
    return outcome;
}

template
Error_code Stack::push(const Stack_entry &item){
// 如果栈满了,则返回overflow的Error_code,
// 否则让item进栈,并且count+1,然后返回success的Error_code
    Error_code outcome = success;
    if(count>=maxstack) {
        outcome = overflow;
    } else {
        entry[count++] = item;
    }
    return outcome;
}

template
Error_code Stack::top(Stack_entry & item) const{
// 后态: 如果栈非空,则将栈顶的元素赋值给item,
//         并且返回success 的Error_code
//      否则,栈空,返回underflow的Error_code
    Error_code outcome = success;
    if(count<=0){
        outcome = underflow;
    } else {
        item = entry[count-1];
    }
    return outcome;
}

main.cpp


#include 
using namespace std;
#include "stack.cpp"
//#include "stack.h"
//使用到模板的时候需要include  对应的类名.cpp
#include "Polynomial.cpp"

int main(){
    int d;
    Stack stack;
    stack.push(1);
    stack.push(2);
    stack.top(d);
    stack.pop();
    cout<
注意,由于这里涉及到了模板,所以在main.cpp里面应该include "stack.cpp",这个时候,就不应在include stack.h。 

另外还有值得一提的是,下面的方法可以防止stack.h被重复include导致效率下降或者重复定义。

#ifndef STACK.H

#define STACK.H


..........stack.h's body...........

#endif.


也就是说如果把stack.h修改成下面这样:

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED

#include "utility.h"   //使用这里面的Error_code
const int maxstack = 1000;

template
class Stack{
public:
    Stack();
    bool empty() const;
    Error_code pop();
    Error_code top(Stack_entry & item) const;
    Error_code push(const Stack_entry &item);
private:
    int count;
    Stack_entry entry[maxstack];
};
#endif // STACK_H_INCLUDED

那么即使在main函数里面,故意地include "stack.cpp" 而且 include "stack.h" 都不会导致出错啦!!!



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