l6_2.cpp

来自「《C++程序设计教程》-杨国兴-电子教案及例题 C++程序设计PPT课件 h」· C++ 代码 · 共 70 行

CPP
70
字号
#include <iostream.h>
#include <string.h>
class  CString    
{
private:
	int  length;
	char *contents;
public:
    CString();        //构造函数
    ~CString();       //析构函数
    int  GetLength();
    void GetContents(char *str);
    void  SetContents(int len, char *cont);
    void  SetContents(char *cont);
};

CString::CString()
{
	length = 0;
	contents = NULL;
    cout << "字符串对象初始化" << endl;
}
CString::~CString()
{
    cout << contents << "被销毁" << endl;
	if(contents != NULL)
		delete contents;
}
int  CString::GetLength()
{
	return  length;
}
void CString::GetContents(char *str)
{
	strcpy(str, contents);
}

void CString::SetContents(int len, char *cont)
{
	length = len;
	if(contents != NULL)
		delete  contents;
	contents = new char[len+1];
	strcpy(contents,cont);
	cout << "两个参数的SetContents函数" << endl;
}
void CString::SetContents( char *cont)
{
	length = strlen(cont);
	if(contents != NULL)
		delete  contents;
	contents = new char[length+1];
	strcpy(contents,cont);
	cout << "一个参数的SetContents函数" << endl;
}

void main()
{
	CString str1;         //两次调用构造函数
	CString str2;         //两次调用构造函数
    str1.SetContents("第一个字符串");
    str2.SetContents(20, "第二个字符串两个参数");
    int  i = str1.GetLength();
	char string[100]; 
	str1.GetContents(string);
    cout << i << "  "<< string << endl;
    i = str2.GetLength();
	str2.GetContents(string);
    cout << i << "  " << string << endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?