新手-为何不包含头文件还可以用string类型
我初学c++,遇到一个问题:在我的测试程序里,我没有包含头文件<string>,但仍然可以使用string类型的变量。然而,如果我去掉<iostream>,编译器就会提示我 “‘string’未声明”.
我认为<iostream>不应该有关于string类型的定义,而且我查看了<iostream>的内容后,也没有发现string.
根据我所学的,"using namespace std; " 仅仅是将多个类的名字打包,其中也没有string的定义。
为什么会出现这种情况呢?
我的编译环境是 ubuntu 9.1 / gcc 4.3, 不过这应该没有什么关系吧?
这是我的测试程序:
/* File name: stack.h
* Definition for the object of stack.
*/
#include <algorithm>
#include <vector>
class Stack {
public:
bool push( const string& );
bool pop( string &elem );
bool peek( string &elem );
bool empty();
bool full();
bool find(const string &elem);
unsigned int count(const string &elem);
int size() { return _stack.size(); }
private:
vector<string> _stack;
};
//为了方便阅读,我省略了具体的函数实现
//主函数如下:
/*
* File name: stack.cpp
* Description: Homework 4.1 from Essential C++
* Enhanced Stack
*/
#include <iostream> //如果注释掉这行,就会报错
using namespace std;
#include "stack.h"
int main (void)
{
Stack s;
string str;
cout << "This is a test for enhanced class Stack." << endl;
s.push("Bin");
s.push("Andy");
s.push("Will");
s.push("Ron");
cout << "The length of s is "<< s.size()<<" Now."<<endl;
cout << "S is full?"<< s.full()<<endl;
cout << "S is empty?"<< s.empty()<<endl;
s.peek(str);
cout << "Let's peek:"<< str <<endl;
s.pop(str);
cout << "Let's pop:"<< str <<endl;
cout << "The length of s is "<< s.size()<<" Now."<<endl;
s.peek(str);
cout << "Let's peek again:"<< str <<endl;
cout << "We can find Bin?"<<s.find("Bin")<<endl;
cout << "We can find Andy"<<s.find("Andy")<<endl;
cout << "Andy position "<<s.count("Andy")<<" Now."<<endl;
cout << "The length of s is "<< s.size()<<" Now."<<endl;
cout << "Say bye to this world, S."<<endl;
cout << "S is empty?"<<s.empty()<<endl;
cout << "The length of s is "<< s.size()<<" Now."<<endl;
s.pop(str);
s.pop(str);
s.pop(str);
cout << "S is empty?"<<s.empty()<<endl;
cout << "The length of s is "<< s.size()<<" Now."<<endl;
return 0;
}