[英]how do I overload the << operator to print the contents of an array in c++?
This is my function, and it is crashing when I run the program. 这是我的功能,运行程序时崩溃。 I am trying to print out the contents of a char array.
我正在尝试打印出char数组的内容。 How do I overload this operator to print out the contents of an array without my program crashing?
如何在不使程序崩溃的情况下重载该运算符以打印出数组的内容?
ostream& operator<< (ostream& out, MyString& obj){
//print out mystring contents
int i = 0;
while(i < obj.size)
{
out << obj.data[i];
i++;
}
}
Here are my data members: 这是我的数据成员:
int size;
int capacity;
char *data;
I made the following modifications, but it still crashes: 我进行了以下修改,但仍然崩溃:
int i = 0;
while(obj.data[i] != '\0')
{
out << obj.data[i];
i++;
}
return out;
You need to return something if you declared your function as such: 如果这样声明函数,则需要返回一些信息:
return out;
Without it, you have Undefined Behavior, one possible outcome of which is program crash. 没有它,您将拥有未定义行为,其可能的结果之一是程序崩溃。
Please, as you are learning set your compiler to treat warnings as errors. 请在学习时将编译器设置为将警告视为错误。
Just a little tip, as NathanOliver said to you, ostreams are already setup to print character arrays as long as they are null terminated, so as long as obj.data
is a null-terminated string, you can do: 就像NathanOliver对您说的那样,只有一点提示,只要将ostreams设置为打印字符数组,只要它们以null终止即可,因此只要
obj.data
是一个以null终止的字符串,您就可以执行以下操作:
ostream& operator<< (ostream& out, MyString& obj){
//print out mystring contents
if (obj.data != nullptr) // you might need this test, you might not, depending on the internal logic of MyString
out << obj.data;
return out;
}
You want to return your ostream
object: 您想返回您的
ostream
对象:
ostream& operator<< (ostream& out, MyString& obj) {
for (size_t i = 0; i < obj.size; ++i) {
out << obj.data[i] << " ";
}
return out;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.