英文:
forward declaration of std::ostream
问题
以下是您要翻译的内容:
The files are organized as following:
//MyClass.h
#pragma once
namespace std {
class ostream;
};
class MyClass
{
private:
int a;
public:
friend std::ostream& operator<<(std::ostream& o, const MyClass& obj);
};
//MyClass.cpp
#include<iostream>
std::ostream& operator<<(std::ostream& o, const MyClass& obj)
{
o << obj.a << std::endl;
return o;
}
//main.cpp
#include "MyClass.h"
#include<iostream>
int main()
{
MyClass obj;
std::cout << obj;
}
It failed compiling with errors on overloading operator<<
:
Error C2371 'std::ostream': redefinition; different basic types
What's the issue here and how to correct it?
英文:
The files are organized as following:
//MyClass.h
#pragma once
namespace std {
class ostream;
};
class MyClass
{
private:
int a;
public:
friend std::ostream& operator<<(std::ostream& o, const MyClass& obj);
};
//MyClass.cpp
#include<iostream>
std::ostream& operator<<(std::ostream& o, const MyClass& obj)
{
o << obj.a << std::endl;
return o;
}
//main.cpp
#include"MyClass.h"
#include<iostream>
int main()
{
MyClass obj;
std::cout << obj;
}
It failed compiling with errors on overloading operator<<
:
> Error C2371 'std::ostream': redefinition; different basic types
What's the issue here and how to correct it?
答案1
得分: 4
如其他人所指出,“ostream”不是一个类,而是一个模板实例的别名,基本上是“ostream = basic_ostream
您不应在“std”命名空间内声明任何内容(除非C++标准明确允许)。要进行前向声明“ostream”等内容,请在您的头文件中使用#include <iosfwd>
。
或者,只需使用#include <iostream>
,而不是前向声明 — 记住的技术细节较少,编译略慢一些 — 您可以根据自己的判断决定哪种更好。
英文:
As other people noted, ostream
is not a class but an alias to a template instantiation, basically ostream = basic_ostream<char>
. This is an implementation detail of the standard library; it's there because it needs to support also wostream
(which is basic_ostream<wchar_t>
) and possibly other stream types. But other implementations may do it differently (using e.g. source code generation) or very differently (distributing pre-compiled modules). You should not depend on any particular implementation.
You should not declare anything inside the std
namespace (except stuff which the C++ Standard explicitly permits). To forward-declare ostream
and such, use #include <iosfwd>
in your header file.
Alternatively, just do #include <iostream>
instead of forward declaration — less technical details to remember vs slightly slower compilation — do your own judgment on what is better.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论