⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 l6_2.cpp

📁 《C++程序设计教程》-杨国兴-电子教案及例题 C++程序设计PPT课件 html课件 例题
💻 CPP
字号:
#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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -