gpt4 book ai didi

c++ - 在 C++ 中输出时出现段错误

转载 作者:搜寻专家 更新时间:2023-10-31 00:23:15 26 4
gpt4 key购买 nike

我正在尝试打印出一个整数数组。当我尝试如下打印时出现段错误。如果我取消注释“In for loop”,它将打印除数组最后一项之外的所有内容,并且它仍然有段错误。当我取消注释这两个注释(或只是“使用 for 循环完成”)时,一切都正常打印。为什么会发生这种情况,我该如何解决?

for( int i = 0; i < l.usedLength; i++ )
{
//cout << "**********In for loop" << endl;
cout << l.largeInt[ i ];
}
//cout << "**********done with for loop" << endl;

这是全类:

#include "LargeInt.h"
#include <ctype.h>

LargeInt::LargeInt()
{
usedLength = 0;
totalLength = 50;

largeInt = new int[totalLength];
for( int i=0; i<totalLength; i++ )
{
largeInt[i] = 0;
}
}

LargeInt LargeInt::operator+(const LargeInt &l) const
{}

LargeInt LargeInt::operator-(const LargeInt &l) const
{}

LargeInt LargeInt::operator*(const LargeInt &l) const
{}

LargeInt LargeInt::operator/(const LargeInt &l) const
{}

bool LargeInt::operator==(const LargeInt &l) const
{}

ostream& operator<<(ostream &out, const LargeInt &l)
{
cout << "In output" << endl;

if( l.usedLength == 0 )
{
cout << 0;
}
else
{
cout << "In else... NON 0" << endl;

for( int i = 0; i < l.usedLength; i++ )
{
cout << "In for loop" << endl;
cout << l.largeInt[ i ];
}
//cout << "done with for loop" << endl;
}
//cout << "after the if.... all done with output" << endl;
}

istream& operator>>(istream &in, LargeInt &l)
{
char x;
while (std::cin.get(x) && x >= '0' && x <= '9')
{
l.largeInt[ l.usedLength ] = x-48;
l.usedLength++;
//need to check array length and make bigger if needed
}

}

主要内容:

#include <stdlib.h>
#include <iostream>

#include "LargeInt.h"

int main(int argc, char** argv) {

cout << "\nJosh Curren's Assignment #5 - Large Integer\n" << endl;

LargeInt lint;

cout << "Enter a large int: ";
cin >> lint;

cout << "\nYou entered: " << endl;
cout << lint << endl;
cout << endl;


return (EXIT_SUCCESS);
}

最佳答案

您忘记了 ostream& operator<<(ostream &out, const LargeInt &l) 中的最后一行:

return out;

这条线完美地工作。

关于c++ - 在 C++ 中输出时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2307815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com