[Dev-C++] help need for user-conversion operator problem
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: bhadram r. <bha...@ya...> - 2005-08-21 08:55:27
|
Dear friend,
I'd a problem. I'm using user defined conversion function char* to use like
char* ch=s1;(string object name); But the problem is that it is giving compilation error. It cannot able to find the conversion operator char*. Can any body solve my problem. Please help me in this aspect.I'd already defined user conversion operator. But still not working.
String::operator const char*() const
{
return buf;
}
yours friendly,
bhadram
D:\cpppractice\aug20\maincpp.cpp(12) : error C2440: 'initializing' : cannot convert from 'class bhadram::String' to 'char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Error executing cl.exe.
maincpp.obj - 1 error(s), 0 warning(s)
The program is as under:
cpp file is:
# include <iostream.h>
# include <String1.h>
using namespace bhadram;
void main()
{
String s1("kummarasetti");
String s2("veera");
String s3("bhadram");
char* ch=s1;
cout<<ch;
}
header file:
# include <string.h>
namespace bhadram
{
class String
{
private:
int size;
char* buf;
friend ostream& operator<<(ostream& ostr,String& s);
friend istream& operator>>(istream& istr,String& s);
friend String operator+(String ,String);
public:
String(int n=0);
String(const char* c);
String(const String& s);
String& operator=(String& s);
String& operator+=(String& s);
operator const char*() const;
};
String::operator const char*() const
{
return buf;
}
String operator+(String s1,String s2)
{
String tempOb;
tempOb.size=s1.size+s2.size;
tempOb.buf=new char[tempOb.size+1];
strcpy(tempOb.buf,s1.buf);
strcat(tempOb.buf,s2.buf);
return tempOb;
}
String& String::operator+=(String& s)
{
char* temp=new char[size+s.size+1];
int tempSize=size+s.size;
strcpy(temp,buf);
strcat(temp,s.buf);
delete [] buf;
size=tempSize;
buf=new char[tempSize+1];
strcpy(buf,temp);
return *this;
}
String& String::operator=(String& s)
{
delete [] buf;
size=s.size;
buf=new char[size+1];
strcpy(buf,s.buf);
return *this;
}
istream& operator>>(istream& istr,String& s)
{
delete [] s.buf;
char tempBuffer[200];
istr>>tempBuffer;
s.size=strlen(tempBuffer);
s.buf=new char[s.size+1];
strcpy(s.buf,tempBuffer);
return istr;
}
ostream& operator<<(ostream& ostr,String& s)
{
return ostr<<s.buf;
}
String::String(const String& s)
{
size=s.size;
buf=new char[size+1];
strcpy(buf,s.buf);
}
String::String(const char* c)
{
size=strlen(c);
buf=new char[size+1];
for(int i=0;i<size;i++)
{
buf[i]=*c++;
}
buf[i]='\0';
}
String::String(int n)
{
if(n==0)
n=1;
size=n;
buf=new char[size+1];
for(int i=0;i<n;i++)
{
buf[i]=' ';
}
buf[i]='\0';
}
};
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com |