07_06.cpp

来自「一些C++的课件和实验源代码」· C++ 代码 · 共 47 行

CPP
47
字号
// 07_06.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string.h>
#include <conio.h>
#include <stdio.h>

class string{
	char * contents;
	int size;
public:
	string (int sz)	{	
		contents = new char[size = sz]; 
		strcpy(contents, "");
	}
	~string(){	
		if (contents != NULL)  delete  []contents;	
	}

	void string::operator = (const string& str)	{
		delete []contents;						// 释放原有内存,以免内存泄露
		contents = new char[size = str.size];	// 分配新内存
		strcpy( contents, str.contents );		// 字符串内容复制
	}

	void  SetValue(char* val) { strcpy(contents, val); }
	char* GetContents()	{	return contents;	}
	int	  GetSize()		{	return size;		}
};

int main(int argc, char* argv[])
{
	string s1(30), s2(20);
	s2.SetValue("njtu");
	s1 = s2;

	printf(" s1.contents = %s, s1.size = %d", 
		s1.GetContents(), s1.GetSize());
	printf("\n s2.contents = %s, s2.size = %d", 
		s2.GetContents(), s2.GetSize());
	printf("\n press any key to exit...");

	getch();
	return 0;
}

⌨️ 快捷键说明

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