我正在测试运算符重载,它似乎与重载的'>>'运算符挂了起来。我输入数字并按回车键,然后光标就位于对我眨眨眼的下一行。

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;
}


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

最佳答案

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,...

关于c++ - cin后程序无响应>>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23233266/

10-15 00:54