-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!
}
関連:https://stackoverflow.com/q/4421706/1896169 – Justin
関連:https://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream –
@ jamarcus_13このオペレータbool演算子<<(const Choco&c){ return this-> full; }少なくともパラメータcが使用されていないため、 は意味がありません:) –