[英]Passing pointer to function that accepts reference in c++
我想這是一個n00b問題,因為我在網上找不到任何有關它的信息...
這是Point類:
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;
};
這是operator <<函數的實現:
inline std::ostream& operator<<(std::ostream& os, const Point& obj) {
os << "(" << obj.getX() << "," << obj.getY() << ")";
return os;
}
現在,在主函數中,我有Point *p;
...如何使用std::cout
打印它?
您需要取消引用指針,但是由於指針可以為null,因此應首先檢查。
if( p != nullptr )
std::cout << *p << std::endl;
甚至只是
if( p )
std::cout << *p << std::endl;
現在,去閱讀我們社區Wiki中的內容,希望它將為您提供答案。
因此,我終於發現問題出在哪里。
盡管所有教程,書籍甚至c ++參考文獻都同意inline
指令可以被編譯器忽略,但事實證明,當我從重載函數的實現中刪除inline
關鍵字時,一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.