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;

}

パンケーキ.h

#ifndef PANCAKE_H
#define PANCAKE_H
#include <string>

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

#endif // PANCAKE_H

パンケーキ.cpp

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

using namespace std;

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

これは、文字列を使用する場合にのみ発生します。整数を使用して、そのすべてのインスタンスを置き換えるstring xと、機能します。しかし、なぜ?int xstring x

4

1 に答える 1

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 ...名前空間を先頭に追加して余分な入力を避け、代わりに受け入れるのが最善の場合があります。

于 2012-07-09T13:30:22.110 に答える