Я создаю класс с именем 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
Как видите, у него есть атрибут типа 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;
}
Моя программа никогда выводит "получает мимо Cin", поэтому .. он не проходит cin
. Проблема в том, что он не читает символ за символом, и я должен быть осторожен, чтобы всегда нажимать ввод после символа. Кто-нибудь знает, как заставить его читать символ за символом?