2013-10-05 119 views
0

如何在函數print中打印指向指向類的類型的指針值print我試着但idk如何打印x和y的指針值指向。 此代碼:如何打印指向指向類C++的指針的值

int main(){ 

#include<iostream> 
using namespace std; 
    class POINT { 
     public: 
      POINT(){ } 
      POINT (int x, int y){ x_=x; y_=y;} 
      int getX(){ return x_; } 
      int getY(){ return y_; } 
      void setX (int x) { x_ = x; } 
      void setY (int y) { y_ = y; } 
     void print() { cout << "(" << x_ << ","<< y_ << ")";} 
     void read() {cin>> x_; cin>>y_;} 
     private:   
      int x_; 
     int y_; 
}; 
void print ( POINT * p1Ptr , POINT * p2ptr){ 
    POINT* x= p1Ptr; POINT*y=p2ptr; 
    cout<<x<<y; 
} 
int main(){ 

POINT p1(3,2); 
POINT p2(6,6); 
    POINT *p1Ptr=&p1; 
    POINT *p2Ptr=&p2; 
    double d=0.0; 
    double *dPtr=&d; 
    p1Ptr->getX(); 
    p2Ptr->getX(); 
    p1Ptr->getY(); 
    p2Ptr->getY(); 
    print (&p1, &p2); 
    system ("pause"); 
    return 0; 
} 
+0

究竟是'print'功能*應該*在做* *除了不必要使得其參數的副本,然後將它們(而不是參數)發送到輸出流? – WhozCraig

+0

實現一個全局函數PrintXY,它接收指向POINT類型對象的指針並打印其數據成員(x和y) –

回答

2

我不能完全肯定這是你的意思,但如何:

class POINT { 
public: 
    // skipped some of your code... 

    void print(std::ostream& os) const 
         // note ^^^^^ this is important 
    { 
     // and now you can print to any output stream, not just cout 
     os << "(" << x_ << ","<< y_ << ")"; 
    } 

    // skipped some of your code... 
}; 

std::ostream& operator<<(std::ostream& os, const POINT& pt) 
{ 
    pt.print(os); 
    return os; 
} 

void print (POINT * p1Ptr , POINT * p2ptr){ 
    cout << *p1Ptr << *p2ptr; 
} 
+0

+1這是一個非常常用的方法(實際上我一直都在使用它)。問題的標題可能會做得更好,因爲「我如何覆蓋自定義類型的流插入運算符?」 – WhozCraig

2

你想 cout << *x << *y;(或 cout << *p1Ptr << *p2ptr;,因爲真的是在複製函數內部的指針 POINT沒有點(雙關語意)!)。

對不起,我認爲有一個operator<<POINT

您需要使用p1ptr->print(); p2ptr->print();才能使用您已有的功能。

+0

我很抱歉它是:cout << * p1Ptr << * p2ptr; –

+0

+1顯示即時和簡單的修復,但我認爲這將有助於OP考慮我的答案的更加靈活和可擴展的解決方案,以便在將來代碼增長時受益。 –

+0

@DanielFrey:是的,這確實是一個「整潔」的修復 - 但是更復雜,可能不是最初的目的,因爲存在「print」功能。 –