K
Kailang Deng
Hi,everybody.
i have a program from More Effective C++ as follows(The code
irrelevant is taken out).
And i am puzzled by the outputs.
class String
{
public:
class CharProxy //proxies for string chars
{
public:
CharProxy(String& str,int index); //constructor
operator char() const
{
cout<<string.data[CharIndex]<<endl; //prints 'r'
return string.data[CharIndex];
}
private:
String& string;
int CharIndex;
};
friend class CharProxy;
String(const char *value=""); //default constructor
String(const String& rhs); //copy constructor
CharProxy operator[] (int index) //subscript operator
{
return CharProxy(*this,index);
}
private:
char *data;
};
int main()
{
String s1("More");
cout<<s1[2]<<endl; //prints 114,not 'r'. why?
return 0;
};
Can anyone explain the output? Thank you very much.
Best Regards.
-Bruce
i have a program from More Effective C++ as follows(The code
irrelevant is taken out).
And i am puzzled by the outputs.
class String
{
public:
class CharProxy //proxies for string chars
{
public:
CharProxy(String& str,int index); //constructor
operator char() const
{
cout<<string.data[CharIndex]<<endl; //prints 'r'
return string.data[CharIndex];
}
private:
String& string;
int CharIndex;
};
friend class CharProxy;
String(const char *value=""); //default constructor
String(const String& rhs); //copy constructor
CharProxy operator[] (int index) //subscript operator
{
return CharProxy(*this,index);
}
private:
char *data;
};
int main()
{
String s1("More");
cout<<s1[2]<<endl; //prints 114,not 'r'. why?
return 0;
};
Can anyone explain the output? Thank you very much.
Best Regards.
-Bruce