8-7.cpp

来自「为C++学习者」· C++ 代码 · 共 50 行

CPP
50
字号
#include<iostream.h>
#include<string.h>
#include<stdlib.h>
class strclass
{
  char *p;
  int length;
public:
  strclass();
  strclass(char *str,int len);
  char *getstring(){return p;}
  int getlength(){return length;}
};
strclass::strclass()
{
  p=new char[255];
  if(!p)
  {
    cout<<"Allocation erroe\n";
	exit(1);
  }
  *p='\0';
  length=255;
}
strclass::strclass(char * str,int len)
{
  if(strlen(str)>=len)
  {
    cout<<"Allcation too little memory! \n";
	exit(1);
  }
  p=new char[len];
  if(!p)
  {
    cout<<"Allocation error\n";
	exit(1);
  }
  strcpy(p,str);
  length=len;
}
main()
{
  strclass ob1;
  strclass ob2("This is a string.",100);
  cout<<"ob1:"<<ob1.getstring()<<"-Allocation length:";
  cout<<ob1.getlength()<<'\n';
  cout<<"ob2:"<<ob2.getstring()<<"-Allocation length:";
  cout<<ob2.getlength()<<'\n';
  return 0;
}

⌨️ 快捷键说明

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