1

したがって、私のプログラムには、Button、Window、および WindowButton といういくつかのクラスがあります。Button はテキストのみで構成され、Window はボタンと座標 (x,y) で構成され、WindowButton は Window で構成されます。WindowButton では、次のように << 演算子をオーバーロードしました。

ostream& operator<<(ostream& out, WindowButton& ref)
{
    ref.print();
    return out;
}

印刷機能は次のようになります。

void WindowButton::print()
{
    theWindow->print();
}

ウィンドウクラスのウィンドウ印刷機能:

void Window::print()
{
    char* buttonText = button->getText();
    char* theText = new char[strlen(buttonText)+1];
    strcpy(theText, buttonText);
    cout << endl << "Window with coordinates (" << this->coord.x << "," << this->coord.y << ") , and button text \"" << theText << "\"" << endl;
}

主に:

WindowButton *test = new WindowButton();
cout << endl << test;
test->print();

最後の行は正しい出力を提供しますが、2 行目はメモリ アドレスのみを提供します。私は何を間違っていますか?test->print(); であるため、すべてが正常に機能するはずです。正常に動作します。

4

3 に答える 3

4

& を期待する operator<< へのポインタを渡しています。

cout << endl << *test;

あなたもそれを作るかもしれません:

ostream& operator<<(ostream& out, const WindowButton& ref){

これは、 print が実際には変更されないことを前提としています。

しかし、より大きな問題は、なぜcoutostream を使用して印刷をトリガーするのかということですtheWindow。これらは (そうではありませんが) 論理的に切断されたプロセスであるように見えます。指定したストリームを Window::print に渡すことができます:

void Window::print(ostream& stream) {

の代わりにそのストリームを使用しますcout。これにより、へのハードコーディングが回避coutされWindow::print()ます。

于 2012-09-16T21:41:11.617 に答える
1

これはポインタであるため、演算子を機能させるには逆参照する必要があります。

cout << endl << *test;
于 2012-09-16T21:40:50.137 に答える
1

この行

cout << endl << test;

へのポインターを出力し、アドレスを出力するポインターの特殊WindowButton化があります。ostream& operator<<ポインターの逆参照を試すことができます。

cout << endl << (*test);

As an aside, there is little point in overloading the ostream& operator<< in a way that eventually just prints to std::cout. The point of such an operator is that you can stream to any ostream, not just cout. You could fix this by modifying your print functions to take an ostream by reference, and modify it:

void WindowButton::print(std::ostream& out) const {
  theWindow->print(out);
}

and

void Window::print(ostream& out) const {
  // stuff
  out << "Window with coordinates (" << this->coord.x << "," << this->coord.y << ") , and button text \"" << theText << "\"" << endl;
}

and finally

ostream& operator<<(ostream& out, const WindowButton& ref){
  ref.print(out);
  return out;
}
于 2012-09-16T21:41:48.983 に答える