一个程序,那位大哥帮忙分析下问题和程序具体是怎么走的呢?
#include <iostream>
#include <cstring>
using namespace std;
class Stringbad //设计一个不好的string类
{
private:
char *str; //1.error:see declaration of 'str'.为什么?
int len;
static int numStrings;
public:
Stringbad();
Stringbad(const char *s);
~Stringbad();
friend ostream & operator << (ostream & os,const Stringbad & st);//2.运算符重载似乎有问题?VC6.0的漏洞?
};
int Stringbad::numStrings = 0;
Stringbad::Stringbad()
{
len = 4;
str = new char[4];
strcpy(str,"c++");
numStrings++;
cout << numStrings << ": \"" << str << "\"default object created" << endl;
}
Stringbad::Stringbad(const char *s)
{
len = strlen(s);
str = new char[len + 1];
strcpy(str,s);
cout << numStrings << ": \"" << str << "\"object created" << endl;
}
Stringbad::~Stringbad()
{
cout << "\"" << str << "\"object deleted, ";
--numStrings;
cout << numStrings << " left" << endl;
delete[]str;
}
ostream& operator << (ostream & os, const Stringbad & st)
{
os << st.str;//3.书上是这样写的,为什么这里不行?友元不能访问对象吗?
return os;
}
void callme1(Stringbad & rsb)
{
cout << "String passed by reference: \n";
cout << " \"" << rsb << "\"\n";
}
void callme2(Stringbad sb)
{
cout << "String passed by value: \n";
cout << " \"" << sb << "\"\n";//error: << is ambiguous
}
int main()
{
Stringbad headline1("Celery Stalks at Midnight");//这三行调用时构造函数要输出三行。
Stringbad headline2("Lettuce Prey");//4.程序是先析构这个对象还是下面的knot?
Stringbad sports("Spinach Leaves Bowl for Dollars");
cout << "headline1: " << headline1 << endl;//再输出三行
cout << "headline2: " << headline2 << endl;
cout << "sports: " << sports << endl;
callme1(headline1);
cout << "headline1: " << headline1 << endl;
callme1(headline2);//5.传值调用会导致析构函数被调用吗?这里输出“lettuce prey "deleted.2 lefted
cout << "headline2: " << headline2 << endl;
cout << "Initialize one object to another: " << endl;
Stringbad sailor = sports; //等价于Stringbad sailor = Stringbad(sports)不知道是调用什么构造函数。
cout << "sailor: " << sailor << endl;
cout << "Assign one object to another: " << endl;
Stringbad knot; //6.第五个对象,这里会调用默认构造函数还是显示构造函数?默认的?numStrings会加一吗?
knot = headline1; //7.这算第五个对象还是第六个?如果算第五个又调用显式构造函数的话numStrings会再加一吗
cout << "knot: " << knot << endl;
cout << "End of main()\n";//析构函数似乎不对劲,程序故意设计的
return 0;
}