LINUX.ORG.RU

[c++][ЧЯДНТ] operator>>

 ,


0

0

#include <iostream>

using namespace std;

#define MAXSIZE 128

class Stack{
public:
Stack();
Stack(int, int*);
Stack(Stack& );
~Stack();
Stack& operator=(Stack&);
void push(int);
bool pop(int&);
friend ostream& operator<<(ostream&, Stack&);
friend istream& operator>>(istream&, Stack&);
private:
int max;
int count;
int *mem;
};

Stack::Stack(){
max=MAXSIZE;
count=0;
mem=new int [MAXSIZE];
}

Stack::Stack(int size, int *p){
max=MAXSIZE;
count=size;
mem=new int [MAXSIZE];
for (int i=0; i<size; i++)
mem[i]=p[i];
}

Stack::Stack(Stack& s){
max=s.max;
count=s.count;
mem=new int[max];
for( int i=0; i<count; i++)
mem[i]=s.mem[i];
}

Stack::~Stack(){
delete[] mem;
}

Stack& Stack::operator=(Stack& s){
if (this!=&s){
delete[] mem;
max=s.max;
count=s.count;
mem=new int[max];
for(int i=0; i<count; i++)
mem[i]=s.mem[i];
}
return *this;
}

void Stack::push(int a){
if(count-1<max){
mem[count]=a;
count++;
}
}
bool Stack::pop(int& a){
if(count>0){
a=mem[count-1];
count--;
return true;
}
return false;
}

ostream& operator<<(ostream& os, Stack& a){
int b;
if (a.pop(b))
os<<b<<endl;
else
os<<«Stack pust.»<<endl;
return os;
}

istream& operator>>(istream& is, Stack& a){
int b;
is >> b;
a.push (b);
return is;
}
---------------вар1
int main(){
Stack *a = new Stack ();
cin >> *a;
cout << *a;
return 0;
}
-------------вар2
int main(){
Stack a();
cin >> a;
cout << a;
return 0;
}

Там стек, при вводе/выводе происходит push/pop соответственно.

Вар1 компилируется и работает, а вар2 - нет, выдает портянку ошибок:
ts.cc: In function ‘int main()’:
ts.cc:93:7: error: ambiguous overload for ‘operator>>’ in ‘std::cin >> a’
/usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/istream:120:7: note: candidates are: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match>
/usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/istream:124:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__ios_type& (*)(std::basic_istream<_CharT, _Traits>::__ios_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>, std::basic_istream<_CharT, _Traits>::__ios_type = std::basic_ios<char>] <near match>
/usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/istream:131:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match>
ts.cc:94:8: warning: the address of ‘Stack a()’ will always evaluate as ‘true’

Вопрос: что каждая из них означает и где я не прав?

★★

Последнее исправление: Dimanc (всего исправлений: 1)
Ответ на: комментарий от yoghurt

>в общем, если нужет хотфикс, томить не буду - из второго варианта скобки убери после a

Не, хотфикс не нужен, объясните.

Dimanc ★★
() автор топика
Ответ на: комментарий от Yareg

> А логичнее и очевиднее было бы, если бы вызвался конструктор по умолчанию...

Не знаю, не знаю =)

yoghurt ★★★★★
()
Ответ на: комментарий от yoghurt

>Ты объявил там функцию, имя которой - a, тип возвращаемого значения - Stack, без параметров.

О как. А такое вообще как возможно?

Dimanc ★★
() автор топика
Ответ на: комментарий от Dimanc

Ну, а выглядит прототип произвольной функции?

ТипВозвращаемогоЗначения Имя ([ОпциональныйСписокАргументов])

Чтобы создать объект на стеке конструктором по умолчанию, пустые скобки в записи ставить не надо - распространённая ошибка.

yoghurt ★★★★★
()
Ответ на: комментарий от yoghurt

>Ну да, почему бы нет. Это же не сама функция, а по сути только forward-declaration

Похоже на правду :) Спасибо.

Dimanc ★★
() автор топика
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.