简体   繁体   中英

Passing pointer to function that accepts reference in c++

I guess this is a n00b question because I couldn't find anything about it on web...

Here is Point class:

class Point {
public:
   Point();
   Point(double x, double y);


   double getX() const;
   double getY() const;
   void setX(double);
   void setY(double);

   friend std::ostream& operator<<(std::ostream& os, const Point& obj);
private:
   double x;
   double y;
};

And here is an implementation of operator<< function:

inline std::ostream& operator<<(std::ostream& os, const Point& obj) {
   os << "(" << obj.getX() << "," << obj.getY() << ")";
   return os;
}

Now, in main function I have Point *p; ... How can I print it using std::cout ?

You need to dereference your pointer but as pointers can be null, you should check first.

if( p != nullptr )
   std::cout << *p << std::endl;

or even just

if( p )
   std::cout << *p << std::endl;

And now, go and read this in our community wiki, hopefully it will provide you the answers.

What are the differences between a pointer variable and a reference variable in C++?

So, I finally found out where was the problem.

Although all tutorials, books and even c++ reference agree that inline directive can be ignored by the compiler, it turns out that when I remove inline keyword from implementation of an overloaded function everything works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM