c++ - 程序永远不会超过>>。那是超载的
问题描述
我正在构建一个名为 的类nim
,其中包含大整数。我班级的标题如下所示:
#ifndef NUMAR_INTREG_MARE_H_INCLUDED
#define NUMAR_INTREG_MARE_H_INCLUDED
#include "array.h"
#include <iostream>
class nim///nim=numar_intreg_mare
{
Array a;//the large integer number
int semn;//the sign of the number
int n;//the length of the number
public:
nim();
nim(nim const &ob);
~nim();
friend std::ostream& operator<<(std::ostream& os, const nim& ob);
friend std::istream& operator>>(std::istream& is, nim& ob);
};
#endif // NUMAR_INTREG_MARE_H_INCLUDED
如您所见,它有一个 type 属性Array
,这是我构建的另一个类。标题Array
是:
#ifndef ARRAY_H_INCLUDED
#define ARRAY_H_INCLUDED
#include <iostream>
class Array{
private:
int* c;
int len, capacity;
public:
Array();
void Append(int);
~Array();
int& operator[] (int) const;
void Afisare();//outputiing the array
friend class nim;
};
#endif // ARRAY_H_INCLUDED
我构建了这个类,以便我可以动态分配内存,正如您从Append
工作原理中看到的那样:
#include "array.h"
#include <iostream>
Array::Array()
{
capacity=1;
c=new int[capacity];
len=0;
}
void Array::Append(int x)
{
int* temp;
if(len>=capacity)
{
temp=new int[2*capacity];
for(int i=0; i<capacity; i++)
{
temp[i]=c[i];
}
capacity*=2;
delete[] c;
c=temp;
}
c[len]=x;
len++;
}
Array::~Array()
{
delete[]c;
}
int& Array::operator[] (int x) const
{
return c[x];
}
void Array::Afisare()
{
for(int i=0; i<len; i++)
std::cout<<c[i]<<" ";
std::cout<<"\n";
}
回到我原来的nim
课程,这就是我实现这些功能的方式:
#include "numar_intreg_mare.h"
#include <iostream>
nim::nim() : semn(0)
{
Array a;
}
nim::nim(nim const &ob) : a(ob.a), semn(ob.semn), n(ob.n){}
nim::~nim(){}
std::ostream& operator<< (std::ostream &os, const nim &ob)
{
if(ob.semn==-1) os<<"-";
else if(ob.semn==1) os<<"+";
for(int i=0; i<ob.n; i++)
{
os<<ob.a[i];
}
os<<"\n";
return os;
}
std::istream& operator>>(std::istream& is, nim &ob)
{
std::cout<<"n=";
int n, semn;
is>>n;
ob.n=n;
std::cout<<"semn=";
is>>semn;
ob.semn=semn;
std::cout<<"a=";
for(int j = 0; j < ob.n; j++)
is >> ob.a[j];
return is;
}
现在,当我main.cpp
看起来像这样时:
#include <iostream>
#include "array.h"
#include "numar_intreg_mare.h"
using namespace std;
int main()
{
nim nr;
cin>>nr;
cout<<"gets past cin";
cout<<nr;
return 0;
}
我的程序从不输出“gets past cin”所以..它没有过去cin
。问题是它不能逐个字符地读取,我必须小心在一个字符后总是按回车键。有谁知道如何让它逐个字符地读取?
解决方案
推荐阅读
- javascript - 来自数组的动态 HTML 行
- amazon-s3 - AWS 胶水将动态帧写入内存不足 (OOM)
- haskell - 是否有一个 Monad 收集结果并将其映射到它们?
- delphi - 未声明的标识符 soAllDirectories
- reactjs - 反应路线不渲染特定组件
- javascript - 为什么我的 javascript 选框不能顺利移动?
- python - 为什么我的 tkinter 标签突然消失了?
- r - 使用 dplyr 对不同长度个体的时间序列组进行平均
- python - model.compile() 在 keras tensorflow 中做了什么?
- mongodb - MongoDB:当 Primary 关闭时,MongoClient 无法连接到辅助副本集