2
//using namespace std;

using std::ifstream;

using std::ofstream;

using std::cout;

class Dog
{

    friend ostream& operator<< (ostream&, const Dog&);

    public:
        char* name;
        char* breed;
        char* gender;

        Dog();
        ~Dog();

};

<<演算子をオーバーロードしようとしています。私も良いコーディングを練習しようとしています。しかし、using名前空間stdのコメントを外さない限り、私のコードはコンパイルされません。私はこのエラーを受け取り続けます、そして私は知りません。g++コンパイラを使用しています。

Dog.h:20: error: ISO C++ forbids declaration of ‘ostream’ with no type
Dog.h:20: error: ‘ostream’ is neither function nor member function; cannot be declared friend. if i add line using std::cout; then i get this error.
Dog.h:21: error: ISO C++ forbids declaration of ‘ostream’ with no type. 

名前空間stdを使用せずに<<演算子をオーバーロードする正しい方法を誰かに教えてもらえますか?

4

2 に答える 2

3

あなたはusing std::ofstreamの代わりに持っているusing std::ostreamので、それは何であるかを知りませんostream

また、を含める必要があります<ostream>

ただし、実際には、使用する理由はありませんusing anything。名前を名前空間で修飾する必要があります(特にこれがヘッダーファイルの場合は、他のファイルのグローバル名前空間を汚染しないようにするため)。

friend std::ostream& operator<< (std::ostream&, const Dog&);
于 2010-04-23T02:12:19.587 に答える
0

キーワードはusing、名前空間の前に付けずに何かにアクセスできるようにすることを意味します。つまり、としてusing std::ofstream;アクセスできるようにするということです。std::ofstreamofstream

#include <iostream>また、 ;が必要なようです。そのため、コンパイラは何であるかを知りませんostream。それを入れて、friend宣言をに変更し、friend std::ostream& operator<< (std::ostream&, const Dog&);すべてのものを取り除きます。ヘッダーusingを入れるのは悪い形式なので、using大丈夫なはずです。

于 2010-04-23T02:15:14.017 に答える