C++输出运算符重载
我一直在做这项学校作业。赋值告诉我们创建一个重载其输出运算符 ( << ) 的对象。 这是我的代码:
#include <ostream>
using namespace std;
template <class T>
class CustomObject {
string print() {
string text = "";
for (int i = 0; i < num_items(); i++) {
text += queue[i];
text += " | \n";
}
return text;
}
friend std::ostream& operator <<(std::ostream &output, CustomObject &q) {
output << "" << q.print();
return output;
}
}
所以我像这样实例化这个对象:
CustomObject<int> co();
并调用它的输出方法:
std::cout << co();
这将不可避免地调用 print 方法,并将字符串返回到默认输出流。
但是,我的控制台/调试器中没有可见的输出。
我在这里缺少什么?
PS,这不是完整的类,它是通用的,因为这里没有必要显示其他一些方法和功能。
PPS num_items() 和队列变量是所说的其余部分,这个类是一个 PriorityQueue 对象。因此,queue 是指定类型的数组(因此是通用声明),num_items() 仅返回数组的计数。
I've been working on this school assignment. The assignment told us to make an object which had it's output operator ( << ) overloaded.
Here's my code:
#include <ostream>
using namespace std;
template <class T>
class CustomObject {
string print() {
string text = "";
for (int i = 0; i < num_items(); i++) {
text += queue[i];
text += " | \n";
}
return text;
}
friend std::ostream& operator <<(std::ostream &output, CustomObject &q) {
output << "" << q.print();
return output;
}
}
So I instantiate this object like this:
CustomObject<int> co();
and call its output method:
std::cout << co();
Which would inevitably call the print method, and return the string to the default output stream.
But, there's no visible output in my console/debugger.
What am I missing here?
PS this is not the complete class, it's generic because of several other methods and functionality that is not necessary to be shown here.
PPS the num_items() and queue variables are part of said rest, this class is a PriorityQueue object. So, queue is an array of the specified type (hence the generic declaration) and num_items() just returns the count of the array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个函数声明。省略括号。
为什么要将
operator()
应用于co
?再次省略括号。这应该可行:唉,从 print 方法构建和返回字符串并不是惯用的 C++。这是我要做的:
That's a function declaration. Leave out the parenthesis.
Why are you appling
operator()
toco
? Again, leave out the parenthesis. This should work:Alas, building and returning a string from a print method is hardly idiomatic C++. Here is what I would do:
如果您希望能够打印临时对象,则应该将该参数设置为常量引用:
If you want to be able to print temporary objects a well, you should make the parameter a const reference: