2017-11-08 10 views
-2

C++の基本的な継承の概念を練習していて、カスタムクラスオブジェクトを印刷してオーバーロードを書いた後、ガイドに従って、印刷のために新しい演算子の使用を登録していません(< <)。印刷オペレータの過負荷は失敗しますか?

誤って入力されたり、宣言/開始エラーが発生しているのでしょうか?

「演算子< <」(オペランドの型が 「のstd :: basic_ostream」と「チョコ」です)のstd :: coutの< < "チョコ値:" の一致なし < <子< <てendl;

#include <iostream> 
using namespace std; 

class Sweets { 
     public: 
       // pure virtual, child MUST implement or become abstract 
       // Enclosing class becomes automatically abstract - CANNOT instantiate 
       virtual bool eat() = 0; 
}; 

// public inheritance : public -> public, protected -> protected, private only accessible thru pub/pro members 
class Choco : public Sweets { 
     public: 

       bool full; 

       Choco() { 
         full = false; 
       } 

       // Must implement ALL inherited pure virtual 
       bool eat() { 
         full = true; 
       } 

       // Overload print operator 
       bool operator<<(const Choco& c) { 
         return this->full; 
       } 
}; 

int main() { 

// Base class object 
//sweets parent; 
Choco child; 

// Base class Ptr 
// Ptr value = address of another variable 
Sweets* ptr; // pointer to sweets 
ptr = &child; 

std::cout<< "Sweets* value: " << ptr << endl; 
std::cout<< "Choco address: " << &child << endl; 
std::cout<< "Choco value: " << child << endl; // Printing causes error! 
} 
+0

関連:https://stackoverflow.com/q/4421706/1896169 – Justin

+1

関連:https://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream –

+0

@ jamarcus_13このオペレータbool演算子<<(const Choco&c){ return this-> full; }少なくともパラメータcが使用されていないため、 は意味がありません:) –

答えて

0

それはクラスのメンバではないため、オペレータは、クラス外部次のように定義されます。

std::ostream & operator <<(std::ostream &os, const Choco &c) 
{ 
    return os << c.full; 
} 

はタイプ boolの発現とreturn文を持たなければならない機能

bool eat() { 
    full = true; 
} 

ことを考慮してくださいまたは、それはベースと派生クラスでの戻り値の型voidで宣言する必要があります。

関連する問題