簡體   English   中英

類中的ostream沒有類型

[英]ostream in class does not have a type

剛接觸C ++,我有一個簡短的問題。

編譯后

g++ *.cpp -o output

我收到此錯誤:

error: 'ostream' in 'class Dollar' does not name a type

這是我的三個文件:

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;
}

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";
}

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

謝謝您的寶貴時間,一切都會有所幫助!

您的代碼中有許多錯誤。

  1. 您經常使用using namespace std 這是一個壞習慣 特別是,這導致您遇到錯誤:您在Dollar.h沒有using namespace std ,因此編譯器不知道ostream含義。 也可以在Dollar.h using namespace std ,或者最好停止使用它並直接指定std命名空間,如std::ostream
  2. 您可以在標頭中使用std::ostream ,但不要在其中包含相應的標准庫標頭<ostream><ostream>包含std::ostream類的定義;對於完整的I / O庫,請包含<iostream> )。 真正的好習慣是將標頭的所有依賴項包括在標頭本身中,以便它是獨立的並且可以安全地包含在任何位置。
  3. 您正在實現帶有簽名std::ostream & operator << (std::ostream &, Dollar const &)的流輸出運算符,這是完全有效的。 但是,您將其稱為指向類型Dollar指針 您應該使用對象本身而不是指針來調用它,因此您應該取消引用指針: std::cout << *cp;
  4. 您為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 } 

您需要在Dollar.h中#include <iostream> ,以便編譯器可以解析std::ostream & operator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM