在cin>>之后程序无响应

时间:2014-04-23 01:31:33

标签: c++

我正在测试运算符重载,似乎是因为重载'>>'而挂断了运营商。我输入数字然后按回车键,然后光标就在下一行对我眨眼。

的main.cpp

#include <iostream>
using std::cout;
using std::endl;
using std::cin;

#include "OpTesting.h"

int main() {

    Testing tObject(8);
    Testing tObject2;

    cout<<"\nEnter 7 numbers" <<endl;
    cout<<":: ";
    cin>>tObject;

    cout<<"\nFirst object contents: ";
    cout<<tObject;

    cout<<"\nAssigning contents of first object to second object" <<endl;
    tObject = tObject2;

    cout<<"\nContents of second object: ";
    cout<<tObject2;

    return 0;
}

功能定义

Testing::Testing(int arraySize) : length(arraySize) {

    cout<<"Object initialized" <<endl;
    ptr = new int[length];

    for(int x = 0; x < length; x++) {
        ptr[x] = 0;
    }

}
Testing::Testing(const Testing &toBeCopied) {

    for(int x = 0; x < length; x++) {
        ptr[x] = toBeCopied.ptr[x];
    }
}

Testing::~Testing() {

    delete[] ptr;

}

const Testing &Testing::operator=(const Testing &toBeAssigned) {

    for(int x = 0; x < length; x++) {
        ptr[x] = toBeAssigned.ptr[x];
    }

    return toBeAssigned;
}

ostream &operator<<(ostream &output, const Testing &data) {

    for(int x = 0; x < data.length; x++) {
        output <<data.ptr[x];
        if(x == data.length) {
            cout<<endl;
        }
    }

    return output;
}

istream &operator>>(istream &input, Testing &data) {

    for(int x = 0; x < data.length; x++) {
        input >> data.ptr[x];
    }

    return input;
}

我尝试在此网站上搜索解决方案,但没有一个答案适用于我。

2 个答案:

答案 0 :(得分:1)

Testing tObject(8);
...
cout<<"\nEnter 7 numbers" <<endl;
cout<<":: ";
cin>>tObject;

这似乎会尝试解析8个数字,而不是7.您尝试输入8个数字吗?

另外关于“我输入数字并点击输入”,用空格分隔单个数字并输入将是相同的,这可能会造成混淆。


此外,此条件语句永远不会运行,x最多只能data.length - 1

    if(x == data.length) {
        cout<<endl;
    }

此外,复制构造函数没有正确设置lengthptr,而operator=也没有设置return *this,...

答案 1 :(得分:1)

Testing tObject(8);
cout<<"\nEnter 7 numbers" <<endl;
cin>>tObject;

您创建长度为8的tObject,然后提示输入7个数字。我猜你会输入7个数字,所以它等待第8个数字......