Kyl*_*yle 2 c++ inheritance header-files istream ostream
刚进入C++,我有一个简单的问题.
编译完成后
g++ *.cpp -o output
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
error: 'ostream' in 'class Dollar' does not name a type
Run Code Online (Sandbox Code Playgroud)
这些是我的三个文件:
main.cpp中
#include <iostream>
#include "Currency.h"
#include "Dollar.h"
using namespace std;
int main(void) {
Currency *cp = new Dollar;
// I want this to print "printed in Dollar in overloaded << operator"
cout << cp;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Dollar.cpp
#include <iostream>
#include "Dollar.h"
using namespace std;
void Dollar::show() {
cout << "printed in Dollar";
}
ostream & operator << (ostream &out, const Dollar &d) {
out << "printed in Dollar in overloaded << operator";
}
Run Code Online (Sandbox Code Playgroud)
Dollar.h
#include "Currency.h"
#ifndef DOLLAR_H
#define DOLLAR_H
class Dollar: public Currency {
public:
void show();
};
ostream & operator << (ostream &out, const Dollar &d);
#endif
Run Code Online (Sandbox Code Playgroud)
谢谢你的时间,一切都有帮助!
您在代码中有许多错误.
using namespace std.这是一种不好的做法.特别是,这导致了你所面对的错误:你没有using namespace std在Dollar.h,所以编译器不知道是什么ostream意思.要么把using namespace std在Dollar.h太,或更好的只是停止使用,并指定std直接命名,如std::ostream.std::ostream在标题中使用,但不包含相应的标准库标题<ostream>(<ostream>包含std::ostream类的定义;包括完整的I/O库<iostream>).一个非常好的做法是在标题本身中包含标题的所有依赖项,以便它是自包含的并且可以安全地包含在任何地方.std::ostream & operator << (std::ostream &, Dollar const &),这非常有效.但是,您将其称为指向类型的指针Dollar.你应该用对象本身而不是指针来调用它,所以你应该取消引用指针:std::cout << *cp;.您为Dollar类实现了输出运算符,但将其用于类型的变量Currency:这将不起作用.有一种方法可以做到这一点 - 确实存在虚拟方法.但是,在这种情况下,操作员是自由功能,因此它不能是虚拟的.所以,你应该print在你的Currency类中添加一个虚方法,实现它Dollar,并从输出操作符调用它:
#include <iostream>
class Currency {
public:
virtual void print (std::ostream &) const = 0;
};
class Dollar : public Currency {
void print (std::ostream & out) const override {
out << "A dollar";
}
};
std::ostream & operator << (std::ostream & out, Currency const & c) {
c.print(out);
return out;
}
int main(/* void is redundant here */) {
Currency *cp = new Dollar;
std::cout << *cp;
// return 0 is redundant in main
}
Run Code Online (Sandbox Code Playgroud)