2012-07-09 43 views
1

我是初學者。我不知道爲什麼我不能使用字符串。它說string does not have a type使用字符串的問題

的main.cpp

#include <iostream> 
    #include <string> 
    #include "Pancake.h" 

using namespace std; 

int main() { 

    Pancake good; 

    good.setName("David"); 

    cout << good.name << endl; 

} 

Pancake.h

#ifndef PANCAKE_H 
#define PANCAKE_H 
#include <string> 

class Pancake { 
    public: 
     void setName(string x); 
     string name; 
    protected: 
    private: 
}; 

#endif // PANCAKE_H 

Pancake.cpp

#include <iostream> 
#include "Pancake.h" 
#include <string> 

using namespace std; 

void Pancake::setName(string x) { 
    name = x; 
} 

這僅發生當我使用字符串時。當我使用整數並在string x的所有實例中將string x替換爲int x時,它就可以工作。但爲什麼?

回答

7

你只是離開了命名空間中你的頭文件:

#ifndef PANCAKE_H 
#define PANCAKE_H 
#include <string> 

class Pancake { 
    public: 
     void setName(std::string x); 
     std::string name; 
    protected: 
    private: 
}; 

#endif // PANCAKE_H 

這可能是最好避免using namespace ...,而是與前面加上命名空間接受額外的輸入。

+0

它的工作原理。謝謝,但你爲什麼說不使用'使用命名空間'? – 0x499602D2 2012-07-09 13:35:43

+0

避免無意的衝突;但這是個人喜好,並非必要。 – user7116 2012-07-09 13:39:01