一、改错题(两处错误)
#include <cstdio>
#include <cstdlib>
char* getErrorType(int nErrorID)
{
char strErrorID1[] = "no exit";
char strErrorID2[] = "not available";
/*改为
char* strErrorID1 = "no exit";
char* strErrorID2 = "not available";
*/
switch(nErrorID)
{
case 1:
return strErrorID1;
case 2:
return strErrorID2;
default:
return NULL;
}
}
void PrintError(int nErrorID)
{
char *strErrorType = getErrorType(nErrorID);
printf("the Error type of ErrorID(%d) is %s\n", nErrorID, strErrorType );
}
int main(int argc, char* argv[])
{
PrintError(1);
PrintError(2);
system("PAUSE");
}
其中主要问题是一个是数组类型,一个指针类型,数组的元素值存储在栈上,而指针的地址在栈上,指针指向的内容在堆上,当函数执行完成时,栈上的相关临时变量和参数都被清除了,这时数组的指针指向内容是随机的,不能把这些临时变量的指针返回给调用者;strErrorID1中的“no exit”是常量字符串,位于静态存储区,它在程序生命期内恒定不变。无论什么时候它始终是同一个“只读”的内存块。
详细可参看:http://blog.csdn.net/bigloomy/article/details/6562105
二、String类构造函数、析构函数、拷贝构造函数与赋值构造函数
#include<iostream>
#include<string>
using namespace std;
class String
{
public:
String(char *str); //Constructor
~String(); //Destructor
String(const String &other); //Copy Destructor
String& operator =(const String& other); //Assignment constructor
/*String operator =(const String other);*/
const char* GetString(); //Display
private:
char* m_data;
};
//Constructor
String::String(char* str)
{
if(str==NULL)
{
m_data=new char[1];
*m_data='\0';
}
else
{
int len=strlen(str);
m_data=new char(len+1);
strcpy(m_data,str);
}
}
//Destructor
String::~String()
{
delete m_data;
}
//Copy Destructor
String::String(const String& other)
{
int len=strlen(other.m_data);
m_data=new char(len+1);
strcpy(m_data,other.m_data);
}
//Assignment constructor
String& String::operator =(const String& other)
{
if(this==&other)
{
return *this;
}
delete [] m_data;
int len=strlen(other.m_data);
m_data=new char(len+1);
strcpy(m_data,other.m_data);
return *this;
}
String& String::operator =(const String other)
{
delete [] m_data;
int len=strlen(other.m_data);
m_data=new char(len+1);
strcpy(m_data,other.m_data);
return *this;
}
//Display
const char* String::GetString()
{
return m_data;
}
int main()
{
String a("hello");
cout<<a.GetString()<<endl;
String b("world");
String c(b);
cout<<c.GetString()<<endl;
String d=c;
cout<<d.GetString()<<endl;
system("PAUSE");
return 0;
}
三、String类型的字符替换
将string中出现的’[’与’]’分别替换成’(’和’)’;
void mystrReplace(string& strTmp)
{
for (int i = 0; i < strTmp.size(); i++)
{
if ('[' == strTmp[i])
{
strTmp[i] = '(';
}
else if(']' == strTmp[i])
{
strTmp[i] = ')';
}
}
}
四、进制之间转换
把long num转换成B进制输出
例如:100转换成8进制 输出为:144
int main()
{
long num;
int B;
func(num,B);
return 0;
}
void func(long num,int B)
{
cout<<"("<<num<<")10 == (";
int remainder,index=0,reuslt[100];
while (num)
{
remainder = num%B;
num = num/B;
reuslt[index] = remainder;
index++;
}
for (int i = index-1; i >= 0; i--)
{
if (reuslt[i] >= 10)
{
cout<<(char)(reuslt[i]+55);
}
else
{
cout<<reuslt[i];
}
}
cout<<")"<<B<<endl;
}