这里是类如何重载<<操作符以打印类成员?
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