GreenCppC 2008-8-24
=========================================
// I 类,对象,函数重载
//-------- From C to C++ ------------
// A simple C Program!
// convert a string to uppercase!
#include
#define N 200
int main(){
char ms[N]; int i;
printf("Input ms: ");
gets(ms);
for(i=0;ms[i];i++)
if(ms[i]>='a'&&ms[i]<='z')
ms[i]-='\x20';
puts(ms);
return 0;
}
/*
path d:\wingw\bin
gcc abc.c -o abc.exe
*/
//------------------------------
// A better C Program!
#include
#define N 200
void strUpper(char *s);
void strLower(char *s);
int main(){
char ms[N];
printf("Input ms: ");
gets(ms);
strUpper(ms);
puts(ms);
strLower(ms);
puts(ms);
return 0;
}
void strUpper(char *s)
{
for(;*s;s++)
if(*s>='a'&&*s='A'&&*s<='Z')*s+='\x20';
}
//------------------------------
// A C++ Program without class and object!
#include
using namespace std;
const int N=200;
void strUpper(char *s);
void strLower(char *s);
int main(){
char ms[N];
cout<<"Input ms: ";
cin.getline(ms,N);
strUpper(ms);
cout<<ms<<"\n";
strLower(ms);
cout<<ms<='a'&&*s='A'&&*s<='Z')*s+='\x20';
}
//------------------------------
// A C++ Program with class and object!
#include
using namespace std;
const int N=200;
class Str{
char s[N];
public:
void out(){cout<<s<<"\n";}
void in(){cout<='a'&&*p='A'&&*p>a.s; //error!
a.in();
a.upper();
a.out();
a.lower();
a.out();
return 0;
}
=========================================
// II. 构造与析构函数
#include
#include
using namespace std;
class child {
char name[20];
int age;
public:
child();
child(char *n,int a);
void ask(char *n);
void ask(int a);
~child();
};
// ---
child::child(){
strcpy(name,"Tomme");
age=3;
}
// ---
child::child(char *name,int age){
strcpy(this->name,name);
this->age=age;
// this -- address of self object
}
// ---
void child::ask(char *n){
if(!strcmp(name,n))
cout<<"Yes, i am "<<n<<".\n";
else
cout<<"No, i am not "<<n<age==age)
cout<<"Yes, i am "<<age<<" years old.\n";
else
cout<<"No, i am not "<<age<<" years old.\n";
}
// ---
child::~child(){
cout<<name<<": Bye!\n";
}
//----------
int main(){
child tom,rose("Rosie",4);
tom.age=4; // error!
tom.ask("tom");
rose.ask("Alice");
tom.ask(2);
return 0;
}
=========================================
// III. 继承
#include
#include
using namespace std;
class child {
protected: //note this change!
char name[20];
int age;
public:
child();
child(char *n,int a);
void ask(char *n);
void ask(int a);
};
// ---
child::child(){
strcpy(name,"Tomme");
age=3;
}
// ---
child::child(char *n,int a){
strcpy(name,n);
age=a;
}
// ---
void child::ask(char *n){
if(!strcmp(name,n))
cout<<"Yes, i am "<<n<<".\n";
else
cout<<"No, i am not "<<n<<".\n";
}
// ---
void child::ask(int a){
if(a==age)
cout<<"Yes, i am "<<a<<" years old.\n";
else
cout<<"No, i am not "<<a<<" years old.\n";
}
// -----------
class pupil: public child{
char book[20];
public:
pupil(char *n,int a,char *b);
void list();
};
// ---
pupil::pupil(char *n,int a,char *b):
child(n,a) {
strcpy(book,b);
}
// ---
void pupil::list()
{
cout<<name<<" "<<age<<" "<<book<<"\n";
}
//----------
int main(){
child tom,rose("Rosie",4);
tom.ask("tom");
rose.ask("Alice");
tom.ask(2);
pupil green("Green",9,"Nature");
green.ask("Jack");
green.ask(10);
green.list();
return 0;
}
=========================================
// IV. 增加与基类成员函数同名的函数;
// 调用基类成员函数;内联函数(in-line)
#include
#include
using namespace std;
class child {
protected:
char name[20];
int age;
public:
child();
child(char *n,int a);
void ask(char *n);
void ask(int a);
};
// ---
child::child(){
strcpy(name,"Tomme");
age=3;
}
// ---
child::child(char *n,int a){
strcpy(name,n);
age=a;
}
// ---
void child::ask(char *n){
if(!strcmp(name,n))
cout<<"Yes, i am "<<n<<".\n";
else
cout<<"No, i am not "<<n<<".\n";
}
// ---
void child::ask(int a){
if(a==age)
cout<<"Yes, i am "<<a<<" years old.\n";
else
cout<<"No, i am not "<<a<<" years old.\n";
}
// -----------
class pupil: public child{
char book[20];
public:
pupil(char *n,int a,char *b);
void ask(char *n){child::ask(n);} // in-line!
void ask(int a){child::ask(a);}
void ask();
};
// ---
pupil::pupil(char *n,int a,char *b):
child(n,a) {
strcpy(book,b);
}
// ---
void pupil::ask()
{
cout<<name<<" "<<age<<" "<<book<<"\n";
}
//----------
int main(){
child tom,rose("Rosie",4);
tom.ask("tom");
rose.ask("Alice");
tom.ask(2);
pupil green("Green",9,"Nature");
green.ask("Jack");
green.ask(10);
green.ask();
return 0;
}
=====================================
// V. 对象数组
#include
using namespace std;
class C1{
int a,b;
public:
C1(int m,int n){a=m;b=n;}
int getAdd(){return a+b;}
};
int main()
{C1 ob[3]={C1(1,2),C1(3,4),C1(5,6)};
int i;
for(i=0;i<3;i++)
cout << ob[i].getAdd() << " ";
// C1 oe[2]; -- Error! means constructor is C1()
// -- need reload C1::C1(){ ... }
// -- eg, C1::C1(){a=b=0;}
return 0;
}
=========================================
// VI. 指向对象的指针
C1 obA(2,3), *p;
p=&obA;
cout <getAdd();
//-------------
C1 ob[3]={C1(1,2),C1(3,4),C1(5,6)}, *q;
q=ob;
for(int i=0;i<3;i++)
{cout <getAdd() << " ";
q++;
}
//-------------
class C2{
public:
int a;
C2(int k){a=k*k;}
};
// . . .
C2 obB(9);
int *p;
p=&obB.a; // Note! a is public, p to member
cout << *p;
// 指向派生类的指针
class Base{
public:
int a,b;
Base(int m,int n){a=m;b=n;}
int getAdd(){return a+b;}
};
class Derived: public Base{
int c;
public:
Derived(int x,int y,int z):
Base(x,y) {c=z;}
float getAve(){return (a+b+c)/3.0F;}
};
// ...
Base *bp;
Derived d(6,7,9);
bp=&d;
cout <getAdd();
cout <getAve(); // Error!
cout <getAve();
=========================================
// VII. 动态分配:new, delete
#include
#include
using namespace std;
int main()
{int *p;
try{
p=new int;
} catch(bad_alloc ex){
cout << "New failed!\n";
return -1;
}
*p=20;
cout << "At "<<p<<" is "<< *p <<"\n";
delete p;
return 0;
}
//-------------
#include
#include
using namespace std;
int main()
{int *p;
try{
p=new int[6];
} catch(bad_alloc ex){
cout << "New failed!\n";
return -1;
}
float ave=0.0F;
int i;
cout<<"Enter numbers: ";
for(i=0;i>p[i];
ave+= *(p+i);
cout<< *(p+i);
}
ave/=6.0F;
cout << "Ave = "<< ave <<"\n";
delete [] p;
return 0;
}
//-------------
#include
#include
#include
using namespace std;
class Balance{
char name[40];
double curValue;
public:
Balance(char *n,double v){ strcpy(name,n);
curValue=v; }
void getValue(char *n,double &v){
strcpy(n,name);
v=curValue;
}
};
int main()
{
Balance *p; char s[40]; double bal;
try{
p=new Balance("Robin Hood",3536.45);
} catch(bad_alloc ex){
cout <getValue(s,bal);
cout<<s<<"\'s balance is "<<bal<<"\n";
delete p;
return 0;
}
=========================================
// VIII. 传递引用
#include
using namespace std;
void neg1(int k);
void neg2(int *p);
void neg3(int &k);
int main()
{
int x=20;
neg1(x);
neg2(&x);
cout << x<< "\n";
neg3(x);
cout << x<< "\n";
}
// - - -
void neg1(int k)
{ k=-k;}
void neg2(int *p)
{ *p=-*p;}
void neg3(int &k)
{ k=-k; }
//-------------
#include
using namespace std;
class C1{
public:
int k;
void neg(C1 &o){o.k=-o.k;}
// -- no temp object created
};
int main()
{
C1 ob;
ob.k=20;
ob.neg(ob);
cout << ob.k < white, and black!
NOT: !black and ,white
*/
#include
#include
#include
#include
using namespace std;
const int N=200;
/* - - - - - - */
class CharStack{
const int StkLen;
char *data;
int top;
public:
CharStack();
~CharStack(){delete []data;}
int push(char x)
{if(top>=StkLen-1)return -1; // it's full
top++;
data[top]=x;
return 0;
}
int pop(char &x)
{if(top<=-1)return -1; // empty!
x= *(data+top);
top--;
return 0;
}
};
CharStack::CharStack():StkLen(40)
{try{
data=new char[StkLen];
}catch(bad_alloc){cout<<"New failed!"; exit(-1);}
top=-1;
}
// ---------
class WordRev{
char ms[N];
public:
void reads()
{ cout<<"Input str:\n";
cin.getline(ms,N);
}
void prints()
{ cout<<ms<<"\n";
}
void wRev();
};
void WordRev::wRev()
{CharStack stk;
int i=0,wStart,wEnd;
while(ms[i])
{if(!isalpha(ms[i]))i++;
else
{wStart=i;
while(isalpha(ms[i]))stk.push(ms[i++]);
wEnd=i;
i=wStart;
while(!stk.pop(ms[i]))i++;
i=wEnd;
}
}
}
// ---------
int main()
{
WordRev sr;
sr.reads();
sr.wRev();
sr.prints();
return 0;
}
=========================================
// IX 函数形参使用默认值
#include
#include
using namespace std;
// -----------
class pupil{
public:
char name[20];
int age;
char book[20];
pupil(char *n,int a,char *b);
void list();
};
// ---
pupil::pupil(char *n,int a,char *b){
strcpy(name,n);
age=a;
strcpy(book,b);
}
// ---
void pupil::list()
{
cout<<name<<" "<<age<<" "<<book<g++ pupil.cpp -o pupil.exe
pupil.cpp: In function `void nextYear(pupil&, char*)':
pupil.cpp:41: error: default argument given for parameter 2 of `void nextYear(pupil&, char*)'
pupil.cpp:25: error: after previous specification in `void nextYear(pupil&, char*)'
*/
=========================================
// X. 虚函数 virtual
#include
using namespace std;
class base{
public:
virtual void vf(){cout<<"base's vf.\n";}
};
class derived1:public base{
public:
virtual void vf(){cout<<"derived1's vf.\n";}
};
class derived2:public base{
public:
virtual void vf(){cout<vf();
p=&d1;
p->vf(); // derived1's vf.
p=&d2;
p->vf(); // derived2's vf.
f(b);
f(d1); // derived1's vf.
f(d2); // derived2's vf.
return 0;
}
=========================================
// XI. 对象赋值问题
#include
#include
#include
using namespace std;
class Myclass{
int *p;
public:
Myclass(int i);
void show(){cout<< *p<<"\n";}
~Myclass(){delete p;}
};
Myclass::Myclass(int i){
try{
p=new int;
} catch(bad_alloc e)
{cout<< "New failed!\n";
exit(-1);
}
*p=i;
}
int main()
{Myclass a(20);
Myclass b=a; //copy by bits
b.show();
return 0;
// 错误!对象中 p 所指向的内存空间将被释放 2 次!
}
=========================================
// XII. 拷贝构造函数
---- 解决对象参数传递的副作用问题
#include
#include
using namespace std;
class array{
public:
int *p;
int size;
array( ){p=NULL;size=0; };
array(int sz);
array(const array &a);
~array(){if(!p){delete [ ]p; size=0;}}
void input();
};
array::array(int sz){
size=sz;
try{
p=new int[size];
}catch (bad_alloc xa){
cout <<"Alloc failed!";
exit(EXIT_FAILURE);
}
}
array::array(const array &a){
try{
p=new int[a.size];
}catch (bad_alloc xa){
cout <<"Alloc failed!";
exit(EXIT_FAILURE);
}
size=a.size;
for(int i=0;i<size;i++)p[i]=a.p[i];
}
void array::input(){
cout<<"Input "<<size<<" integers: ";
for(int i=0;i>p[i];
}
void inc(array a){
int i;
for(i=0;i<a.size;i++)
if(a.p[i]==59)a.p[i]++;
cout<<"Result is: " ;
for(i=0;i<a.size;i++)cout<<a.p[i]<<' ';
cout<<"\n";
}
int main(){
array a(4),c;
a.input();
array b(a); // 调用拷贝构造函数
inc(b); //调用拷贝构造函数(隐式)
for(int i=0;i<b.size;i++)cout<<b.p[i]<<' ';
return 0;
}
=========================================
// XIII. 运算符重载
#include
using namespace std;
class loc{
int longitude,latitude;
public:
loc(){} //needed to construct temp objects
loc(int lg,int lt){longitude=lg; latitude=lt;}
void show(){cout<<longitude<<" "<<latitude<<"\n";}
loc operator+(loc op2);
loc operator++();
loc operator=(loc op2);
loc operator+=(loc op2);
};
loc loc::operator+(loc op2)
{loc temp;
temp.longitude=op2.longitude+longitude;
temp.latitude=op2.latitude+latitude;
return temp;
}
loc loc::operator++() //前缀形式 prefix
{longitude++;
latitude++;
return *this;
}
loc loc::operator=(loc op2)
{
longitude=op2.longitude;
latitude=op2.latitude;
return *this; //为连续赋值
}
loc loc::operator+=(loc op2)
{
longigude=op2.longitude+longitude;
latitude=op2.latitude+latitude;
return *this; //为连续赋值
}
// operator=和operator++等都改变了对象的值
int main()
{loc ob1(10,20),ob2(5,30),ob3;
ob3=ob1+ob2;
++ob3;
ob3.show();
ob1+=ob2;
ob1=ob1+ob2;
// ob1.+(ob2) like
(ob1+ob2).show();
++ob1;
ob1=ob2=ob3;
... ...
}
=========================================
// XIV. 异常的抛出,捕获与处理
#include
using namespace std;
int main()
{cout <<"Start\n";
try {
cout << "Inside try block\n";
throw 100;
cout << "This will not execute";
}
catch (int i) {
cout << "Caught an exception, value is: ";
cout << i <<"\n";
}
cout << "End\n";
return 0;
}
// --------------------
#include
using namespace std;
void xtest(int test)
{
cout << "Inside xtest!\n";
if(test) throw test;
}
int main()
{cout <<"Start\n";
try {
cout << "Inside try block\n";
xtest(0);
xtest(1);
xtest(2);
}
catch (int i) {
cout << "Caught an exception, value is: ";
cout << i <<"\n";
}
cout << "End\n";
return 0;
}
// 捕获异常类
#include
#include
using namespace std;
class MyException{
public:
char how[80];
int what;
MyException(){*how=0; what=0;}
MyException(char *s, int n)
{strcpy(how,s);
what=n;
}
};
int main()
{int i;
try {
cout <> i;
if(i<0) throw MyException("Not Positive",i);
}
catch (MyException e) {
cout << e.how<<": ";
cout << e.what <<"\n";
}
return 0;
}
// 捕获派生异常类
#include
using namespace std;
class B { };
class D: public B { };
int main()
{D derived;
try {
throw derived;
}
catch (D d) {
cout << "Caught a derived class, not the base! \n";
}
catch (B b) {
cout << "Caught the base class! \n";
}
return 0;
}
// 异常的限制及捕获所有异常
#include
using namespace std;
void xtest(int test) throw (int,char,double,char *)
{
try {
if(test==0) throw test;
if(test==1) throw 'a';
if(test==2) throw 12.34;
if(test==3) throw "A string.";
}
catch (int i) {
cout << "Caught an integer!";
}
catch (...) {
cout << "Caught Another!";
}
}
int main()
{cout <<"Start\n";
xtest(0);
xtest(1);
xtest(2);
xtest(3);
cout << "End\n";
return 0;
}
// 异常的再次抛出
#include
using namespace std;
void xhandler()
{
try {
throw "Hello!";
}
catch (const char *) {
cout << "Caught a string inside!\n";
throw; //rethrow char * out of function
}
}
int main()
{cout <<"Start\n";
try {
xhandler();
}
catch (const char *) {
cout << "Caught a string outside!\n";
}
cout << "End\n";
return 0;
}
// 一个简单的程序
#include
using namespace std;
int main()
{int a,b;
cout <> a >> b;
try {
if(!b) throw b;
cout << "Result: "<< a/b << endl;
}
catch (int i) {
cout << "Can't divide by zero!\n";
}
return 0;
}
=========================================
XV. 模板
//模板之通用函数
#include
using namespace std;
template void superSwap(X &a, X &b)
{
X t;
t=a; a=b; b=t;
};
int main()
{
int m=10, n=20;
double x=10.1, y=20.2;
char a='A', b='\x42';
superSwap(m,n);
superSwap(x,y);
superSwap(a,b);
cout<<"m="<<m<<", n="<<n<<'\n';
cout<<"x="<<x<<", y="<<y<<'\n';
cout<<"a="<<a<<", b="<<b<<'\n';
return 0;
}
----------------------------------
#include
using namespace std;
template
void myfunc(type1 x, type2 y)
{
cout<<x<<' '<<y<<'\n';
}
int main()
{
myfunc("C++ is great!", 100); // char* , int
myfunc(1234.56, 20L); // double , long int
return 0;
}
// 模板之通用类
#include
using namespace std;
const int Size=20;
template class SuperStack{
DataType data[Size];
int top;
public:
SuperStack(){top= -1;}
int push(DataType x);
int pop(DataType &x);
};
template
int SuperStack::push(DataType x)
{
if(top>=Size-1) return -1; // stack is full
data[++top]=x;
return 0;
}
template
int SuperStack::pop(DataType &x)
{
if(top<0) return -1; // stack is empty
x=data[top--];
return 0;
}
int main()
{
SuperStack chStack;
SuperStack dbStack;
char s[Size]="ABC";
double a[Size]={20.1, 21.2, 22.3};
int i;
for(i=0;i<3;i++)
{
chStack.push(s[i]);
dbStack.push(a[i]);
}
for(i=0;i<3;i++)
{
chStack.pop(s[i]);
dbStack.pop(a[i]);
}
cout << s << '\n';
for(i=0;i<3;i++) cout << a[i]<<' ';
cout<<'\n';
return 0;
}
=========================================
XVI. 名字空间
#include
using namespace std;
namespace GreenNamespace{
char Say[80]="TRUTH, Must thou Know!";
bool isUpperLetter(char ch)
{
if(ch>='A' &&ch<='Z')return true;
return false;
}
class X{
public:
int year;
X(int y){year=y;}
}; // note this semi-colon!
}
using namespace GreenNamespace;
int main()
{cout << Say <<'\n';
char *p=Say; int count=0;
for(;*p;p++) if(isUpperLetter(*p))count++;
cout << "count = " << count <<'\n';
X ob(2006);
cout << ob.year <<"\n";
return 0;
}
//------------------------
////////// OneCount.cpp////////
namespace BitsSpace{
int onePerByte(char x);
int oneCount(char *buf,int bytes);
// -------------------
int onePerByte(char x)
{int count=0,i;
for(i=0;i<8;i++)
{if(x & '\x1') count++; // 'A' '\x41'
x>>=1; //x=x>>1;
}
return count;
}
// ---
int oneCount(char *buf,int bytes)
{int count=0,i;
for(i=0;i<bytes;i++)
count+=onePerByte(buf[i]);
return count;
}
// ---
}
----------------
////////// testOne.cpp////////
#include
#include "OneCount.cpp"
using namespace std;
//using namespace BitsSpace;
const int SLen=80;
// ----
int main(){
char ms[SLen],*p;
cout< " ;
cin.getline(ms,SLen);
cout<< BitsSpace::oneCount(ms,strlen(ms))<<"\n";
cout<<"Size of char: "<<sizeof(char)<<"\n";
return 0;
}
=========================================
////////////////////////////////
// XVII. C++ file handle, 6 programs
// by Hs.li 2007.4.28
////////////////////////////////
// Write text strings!
#include
#include
using namespace std;
#define MaxN 200
// - - - - - -
int main()
{fstream outF;
char text[MaxN];
cout<<"Enter lines, end with empty line:\n";
outF.open("str.txt",ios::out);
if(!outF.is_open())
{cout<<"File open failed!\n";
return -1;
}
while(1)
{ cin.getline(text,MaxN);
if(!text[0])break;
outF<<text<<"\n";
if(outF.bad()||outF.fail())
{cout<<"Write file error!\n";
outF.close();
return -2;
}
}
cout<<"Write text file okey!\n";
outF.close();
return 0;
}
=========================
// Read text strings!
#include
#include
using namespace std;
#define MaxN 200
// - - - - - -
int main()
{fstream inF;
char text[MaxN];
cout<<"The text lines are:\n";
inF.open("str.txt",ios::in);
if(!inF.is_open())
{cout<<"File open failed!\n";
return -1;
}
while(1)
{
inF.getline(text,MaxN);
if(inF.eof()|inF.fail()|inF.bad())break;
cout<<text<<"\n";
}
if(!inF.eof())
{cout<<"Read file error!\n";
inF.close();
return -2;
}
cout<<"---- End!\n";
inF.close();
return 0;
}
======================
// Write text data!
#include
#include
using namespace std;
// - - - - - -
int main()
{
const int MaxN=8;
fstream outF;
double a[MaxN];
char *fname="data.txt";
int i;
cout<<"Please input 8 double: ";
for(i=0;i>a[i];
outF.open(fname,ios::out);
if(!outF.is_open())
{cout<<"File open failed!\n";
return -1;
}
outF.exceptions(fstream::failbit|
fstream::badbit);
try{
for(i=0;i<MaxN;i++) outF<<a[i]<<" ";
}
catch(std::exception &e)
{cout<<"Exception caught:"<<e.what()<<endl;
outF.close();
return -2;
}
outF.close();
cout<<"Text data file write okey!\n";
return 0;
}
============================
// Read text data!
#include
#include
using namespace std;
// - - - - - -
int main()
{
fstream inF;
double b;
char *fname="data.txt";
cout<<"Please wait for reading data:\n";
inF.open(fname,ios::in);
if(!inF.is_open())
{cout<>b;
cout<<b<<" ";
}
}catch(std::exception &e)
{
if(!inF.eof())
{
cout<<"Exception caught:"<<e.what()<<endl;
inF.close();
return -2;
}
}
inF.close();
cout<<"\nText data file read okey!\n";
return 0;
}
===============================
// Write binary data!
#include
#include
using namespace std;
// - - - - - -
int main()
{
const int MaxN=8;
fstream outF;
double a[MaxN];
char *fname="data.dat";
int i;
cout<<"Please input 8 double: ";
for(i=0;i>a[i];
outF.open(fname,ios::out|ios::binary);
if(!outF.is_open())
{cout<<"File open failed!\n";
return -1;
}
outF.exceptions(fstream::failbit|
fstream::badbit);
try{
outF.write((char *)a,MaxN*sizeof(double));
}
catch(std::exception &e)
{cout<<"Exception caught:"<<e.what()<<endl;
outF.close();
return -2;
}
outF.close();
cout<<"Binary data file write okey!\n";
return 0;
}
================================
// Read binary data!
#include
#include
using namespace std;
// - - - - - -
int main()
{
fstream inF;
double b;
char *fname="data.dat";
cout<<"Please wait for reading data:\n";
inF.open(fname,ios::in|ios::binary);
if(!inF.is_open())
{cout<<"File open failed!\n";
return -1;
}
inF.exceptions(fstream::failbit|
fstream::badbit|fstream::eofbit);
try{
while(1)
{
inF.read((char *)&b,sizeof(double));
cout<<b<<" ";
}
}catch(std::exception &e)
{
if(!inF.eof())
{
cout<<"Exception caught:"<<e.what()<<endl;
inF.close();
return -2;
}
}
inF.close();
cout<<"\nBinary data file read okey!\n";
return 0;
}
////////////////////////////////////////////////