Your own string class : Your string « Data Types « C++ Tutorial

Home
C++ Tutorial
1.Language Basics
2.Data Types
3.Operators statements
4.Array
5.Development
6.Exceptions
7.Function
8.Structure
9.Class
10.Operator Overloading
11.Pointer
12.File Stream
13.template
14.STL Introduction
15.string
16.vector
17.list
18.bitset
19.set multiset
20.valarray
21.queue stack
22.deque
23.map multimap
24.STL Algorithms Modifying sequence operations
25.STL Algorithms Non modifying sequence operations
26.STL Algorithms Binary search
27.STL Algorithms Sorting
28.STL Algorithms Merge
29.STL Algorithms Min Max
30.STL Algorithms Iterator
31.STL Algorithms Heap
32.STL Algorithms Helper
C / ANSI-C
C Tutorial
C++
Visual C++ .NET
C++ Tutorial » Data Types » Your string 
2.42.1.Your own string class
#include<iostream.h>
#include<string.h>
#include<stdlib.h>

class String
{
  char *p;
  int length;
public:
  String();
  String(char *str,int len);
  char *getstring(){return p;}
  int getlength(){return length;}
};
String::String()
{
  p=new char[255];
  if(!p)
  {
    cout<<"Allocation erroe\n";
       exit(1);
  }
  *p='\0';
  length=255;
}
String::String(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()
{
  String ob1;
  String 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;
}
ob1:-Allocation length:255
ob2:This is a string.-Allocation length:100
2.42.Your string
2.42.1.Your own string class
2.42.2.Define and use a string class
2.42.3.convert between ordinary strings and class String
2.42.4.strings defined using array and pointer notation
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.