本文用到三个文件,./src/mian.cpp ; ./test.h ./makefile
1.<pre name="code" class="cpp">./test.h
#ifndef TEST_H
#define TEST_H
#include <iostream>
#include <string>
using namespace std;
enum gender{male,fmale,couple};
class Person{
string name;
enum gender sex;//declare
string PID;
int salary;
public:
//
Person(string n="kobe",enum gender se=male,string p="000",int sa=8000){
name=n;
sex=se;
PID=p;
salary=sa;
cout<<"initial class"<<endl;
}
//
~Person(){
cout<<"~ ~ ~ ~ ~ ~"<<endl ;
}
//
friend Person& operator + (const Person a,const Person b){
static Person family;
family.name=a.name + " and " +b.name;
family.salary=a.salary+b.salary;
family.PID=a.PID+"-"+b.PID;
if( (a.sex + b.sex == 1) )
family.sex=couple;
return family;
}
//
void show(Person& x) const {
string gender;
if(sex==0)
gender="male";
else if (sex==1)
gender="fmale";
else
gender="couple";
cout<< name <<" , "<< gender <<" , "<< PID <<" , "<<salary<<endl;
}
};
#endif
</pre><pre name="code" class="cpp">2. ./src/main.cpp
<pre name="code" class="cpp">#include"../test.h"
int main()
{
cout<<"cpp test"<<endl;
Person a;
a.show(a);
Person b("Rose",fmale,"333",2000);
b.show(b);
//cout<< (a+b).salary<<endl;
(a+b).show(a+b);//famlie totail salary
}
3../makefile
#makefile start
#define compiler
CC = gcc
GCCXX = g++
#compile paraments
CFLAGS = -Wall -O -g
#OBJ execute file
TARGET = ./helloworld
#cpp PATH
VPATH = ./src/*.cpp ./src/*.c
#../src/test/*.cpp
SRC = $(wildcard $(VPATH))
OBJS = $(patsubst %.cpp,%.o,$(patsubst %.c,%.o,$(SRC)))
###c/cpp compile to .o
%.o: %.cpp
<span style="white-space:pre"> </span>$(GCCXX) $(CFLAGS) -c $^ -o $@
%.o: %.c
<span style="white-space:pre"> </span>$(CC) $(CFLAGS) -c $^ -o $@
###OBJ link
<span style="white-space:pre"> </span>$(TARGET):$(OBJS)
<span style="white-space:pre"> </span>$(GCCXX) $(OBJS) -o $(TARGET)
<span style="white-space:pre"> </span>chmod a+x $(TARGET)
##make clean
clean:
<span style="white-space:pre"> </span>rm -f $(OBJS) $(TARGET) *.*~
###end#########
4,运行结果
/home/guest/cpp/ > ./helloworld
main() begins to run...
initial class
kobe , male , 000 , 8000
initial class
Rose , fmale , 333 , 2000
initial class
kobe and Rose , couple , 000-333 , 10000
~ ~ ~ ~ ~ ~
~ ~ ~ ~ ~ ~
~ ~ ~ ~ ~ ~
~ ~ ~ ~ ~ ~
~ ~ ~ ~ ~ ~
~ ~ ~ ~ ~ ~
~ ~ ~ ~ ~ ~
/home/guest/cpp/ > ./helloworld >log
/home/guest/cpp/ >