2013-10-05 297 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”功能。 –