+ 4
Why is the 1st constructor being called, when I provoke the second one?
I have the following class: class Data { int* dat; int csize; Data(bool z=0 ,int cs=0) { cout<<"Default"<<endl; dat = new int[100]; for(int i=0;i<cs;i++) dat[i]=0; dat[0]=(z?0:1); } Data(string a) { cout<<"Special"<<endl; csize = a.length(); dat =new int[a.length()]; for(int i=0;i<a.length();i++) dat[i] = a.at(a.length()-i-1)-48; } friend ostream& operator<<(ostream&,Data); }; Now, on calling the following in main: Data d("23334"); cout<<d<<endl; The program prints 0. Why?
7 ответов
+ 3
The ostream operator works fine with the 1st constructor...
Also, I copy the size into a variable calles csize, in both constructors...
+ 3
@Immortal
I had to erase it here, Thanks to SoloLearn's 512 char limit...
+ 3
The complete class:
class Data
{
int* dat;
int csize;
Data(bool z=0 ,int cs=0)
{
cout<<"Default"<<endl;
csize = cs;
dat = new int[100];
for(int i=0;i<cs;i++) dat[i]=0;
dat[0]=(z?0:1);
}
Data(string a)
{
cout<<"Special"<<endl;
csize = a.length();
dat =new int[a.length()];
for(int i=0;i<a.length();i++)
dat[i] = a.at(a.length()-i-1)-48;
}
friend ostream& operator<<(ostream& os,Data d)
{
for(int i=csize-1;i>=0;i--)
os<<d.dat[i];
return os;
}
};
+ 3
@Immortal
Yes, and this works, maybe as int can never hold a string, but bool may...
+ 2
I interchanged the bool and the int parameters, and it started working...
So, can i conclude that bool can even analyze strings as true or false?
Thank You for answering!