已知類String的原型爲:
class String
{
public:
String(const char *str = NULL);// 普通構造函數
String(const String &other); //
拷貝構造函數
~ String(void); // 析構函數
String & operator =(const String &other);// 賦值函數
private:
char *m_data;// 用於保存字符串
};
請編寫String的上述4個函數。
//普通構造函數
String::String(const char *str)
{
if(str==NULL)
{
m_data = new char[1]; // 對空字符串自動申請存放結束標誌'\0'的//加分點:對m_data加NULL 判斷
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char[length+1]; // 若能加 NULL 判斷則更好
strcpy(m_data, str);
}
}
// String的析構函數
String::~String(void)
{
delete[] m_data; // 或delete m_data;
}
//拷貝構造函數
String::String(const String &other) // 輸入參數爲const型
{
int length = strlen(other.m_data);
m_data = new char[length+1]; //對m_data加NULL 判斷
strcpy(m_data, other.m_data);
}
//賦值函數
String & String::operator =(const String &other) // 輸入參數爲const
型
{
if(this == &other) //檢查自賦值
return *this;
delete[] m_data; //釋放原有的內存資源
int length = strlen( other.m_data );
m_data = new char[length+1]; //對m_data加NULL 判斷
strcpy( m_data, other.m_data );
return *this; //返回本對象的引用
}
58 如何打印出當前源文件的文件名以及源文件的當前行號?
答案:
cout << __FILE__ ;
cout<<__LINE__ ;
__FILE__和__LINE__是系統預定義宏,這種宏並不是在某個文件中定義的,而是由編譯器定義的。
cout << __FILE__ ;
cout<<__LINE__ ;
__FILE__和__LINE__是系統預定義宏,這種宏並不是在某個文件中定義的,而是由編譯器定義的。
(待續..)
答案:
cout << __FILE__ ;
cout<<__LINE__ ;
__FILE__和__LINE__是系統預定義宏,這種宏並不是在某個文件中定義的,而是由編譯器定義的。