gpt4 book ai didi

c++ - 如何打印指向类c++类型的指针的值

转载 作者:行者123 更新时间:2023-11-27 23:12:30 26 4
gpt4 key购买 nike

如何在函数 print as globe 中打印指向类类型的指针的值,我正在尝试,但我不知道如何打印指针指向的 x 和 y 的值。这段代码:

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;
}

最佳答案

我不太确定这是你的意思,但是怎么样:

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;
}

关于c++ - 如何打印指向类c++类型的指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com