這裏是類如何重載<<操作符以打印類成員?
class graph {
public:
graph() {}; // constructor
graph(int size);
friend ostream& operator<< (ostream& out, graph g);
private:
int size;
bool** grph;
};
我這是怎麼生成的圖形:
graph::graph(int size) {
grph = new bool*[size];
for (int i = 0; i < size; ++i)
grph[i] = new bool[size];
for (int i = 0; i < size; ++i)
for (int j = i; j < size; ++j) {
if (i == j)
grph[i][j] = false;
else {
cout << prob() << endl;//marker
grph[i][j] = grph[j][i] = (prob() < 0.19);
cout << grph[i][j] << endl;//marker
}
}
cout << "Graph created" << endl;//marker
}
構造函數和概率()函數的工作就好了。我已經使用標記測試了它們。
這是我認爲存在問題的地方。這是重載操作< <
ostream& operator<< (ostream& out, graph g) {
for (int i = 0; i < g.size; ++i) {
for (int j = 0; j < g.size; ++j)
out << g.grph[i][j] << "\t";
out << endl;
}
return out;
}
代碼下面是這是怎麼叫。
graph g(5);
cout << g << endl;
現在,程序編譯就好了。但是,執行時,圖形不會被打印。我已經能夠以相同的方式打印圖形而不會重載運算符,但是可以通過讓for循環在main中運行或使用類成員函數來運行。
任何人都可以幫我嗎?我使用Visual Studio 2015年
這個類也將需要重載一些功能,以適應複製。這篇文章應該是有用的:https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – Galik