我知道我們想做這樣的事情來覆寫operator<<
#include <iostream>
class Point
{
private:
double m_x{};
double m_y{};
double m_z{};
public:
Point(double x=0.0, double y=0.0, double z=0.0)
: m_x{x}, m_y{y}, m_z{z}
{
}
friend std::ostream& operator<< (std::ostream& out, const Point& point);
};
std::ostream& operator<< (std::ostream& out, const Point& point)
{
// Since operator<< is a friend of the Point class, we can access Point's members directly.
out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ')'; // actual output done here
return out; // return std::ostream so we can chain calls to operator<<
}
int main()
{
const Point point1{2.0, 3.0, 4.0};
std::cout << point1 << '\n';
return 0;
}
來源:https ://www.learncpp.com/cpp-tutorial/overloading-the-io-operators/
但是如果我不需要訪問私有成員變數怎么辦?我可以繼續使用friend,但我不希望因為我認為這會混淆代碼。但我不知道如何不使用friend. 我試過:
- 只是 drop
friend,但是編譯器會插入隱式this指標作為第一個引數,這不是我想要的。 - 更改
friend為static,但我的 IDE 抱怨operator<<不能是靜態的。
uj5u.com熱心網友回復:
您可以在與(在本例中為全域命名空間)operator<<相同的命名空間中宣告為自由函式,PointADL 會處理它:
#include <iostream>
class Point {
private:
double m_x{};
double m_y{};
double m_z{};
public:
Point(double x = 0.0, double y = 0.0, double z = 0.0)
: m_x{x}, m_y{y}, m_z{z} {}
};
std::ostream& operator<<(std::ostream& out, const Point& point) {
out << "Point";
// Use public interface of point here.
return out;
}
int main() {
const Point point1{2.0, 3.0, 4.0};
std::cout << point1 << '\n';
return 0;
}
uj5u.com熱心網友回復:
同樣的例子,更少的代碼:
class Point
{
friend std::ostream& operator<< (std::ostream& out, const Point& point); // 1
};
// 2
std::ostream& operator<< (std::ostream& out, const Point& point)
{
return out;
}
//1只是宣告這std::ostream& operator<<(std::ostream&,const Point&);是一個friend類。這就是這條線的全部含義。如果您不想將該函式宣告為該類的朋友,則洗掉此行:
class Point {};
std::ostream& operator<< (std::ostream& out, const Point& point)
{
// only access to public members of point
return out;
}
uj5u.com熱心網友回復:
解決這個問題的三種方法:
- 公開 m_x、m_y、m_z
- 添加回傳 m_x、m_y、m_z 的公共 x、y、z 方法
- 添加運算子 << 可以呼叫的公共列印方法
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/472142.html
標籤:C
上一篇:通過函式指標間接完美轉發?
下一篇:測驗自動評估排序演算法的實施細節
