一段C++代码,请能读懂的朋友在每句代码后面用“//”进行标注解释!谢谢!
这学期刚开始学C++,老师给了段代码要我们分析,读不懂啊,而且老师讲知识喜欢穿插讲,很多没学过的内容都写进代码里了!请朋友帮忙!代码如下:第一题:
#include "stdafx.h"
#include "iostream.h"
#include "string.h"
#include "malloc.h"
struct item{
char name[20];
long number;
};
class PhoneBook{
int n;
struct item *p;
public:
PhoneBook(int);
~PhoneBook();
void setname(int,char*);
void setnumber(char*,long);
void print();
};
PhoneBook::PhoneBook(int x){
n=x;
p=(struct item*)calloc(n,sizeof(struct item));
}
PhoneBook::~PhoneBook (){
free(p);
}
void PhoneBook::setname (int a,char* b){
strcpy((p+a)->name ,b);
}
void PhoneBook::setnumber (char* a,long b){
for (int i=0;i<n;i++){
if (strcpy((p+i)->name ,a)==0)
(p+i)->number =b;
}
}
void PhoneBook::print (){
for (int i=0;i<n;i++){
cout<<"name="<<(p+i)->name;
cout<<"number="<<(p+i)->number;
}
}
int main(int argc, char* argv[])
{
PhoneBook a(10);
a.setname(0,"aaaa");
a.setname(1,"bbbb");
a.setname(2,"cccc");
a.setname(3,"dddd");
a.setname(4,"eeee");
a.setnumber("aaaa",1111);
a.setnumber("bbbb",2222);
a.setnumber("cccc",3333);
a.setnumber("dddd",4444);
a.setnumber("eeee",5555);
a.print ();
return 0;
}
第二题:
#include "stdafx.h"
#include "malloc.h"
#include "string.h"
#include "iostream.h"
struct item{
char name[20];
long number;
};
class PhoneBook{ //类的声明
int current;
int n;
struct item *p;
public:
PhoneBook(int);
~PhoneBook();
void setname(int,char*);
void setnumber(int,long);
long& operator()(char*);
PhoneBook& operator()(int);
void operator=(char*);
long operator[](char*);
char* operator[](long);
void print();
};
//类的定义
long PhoneBook::operator [](char* x){
for (int i=0;i<n;i++){
if (strcmp((p+i)->name,x)==0)
return (p+i)->number;
}
}
char* PhoneBook::operator [](long x){
for (int i=0;i<n;i++){
if ( (p+i)->number==x)
return (p+i)->name;
}
}
void PhoneBook::operator =(char* a){
strcpy((p+current)->name, a);
}
PhoneBook& PhoneBook::operator ()(int a){
current=a;
return *this;
}
void PhoneBook::print(){
for (int i=0;i<n;i++)
cout<<"name="<<(p+i)->name<<" number="<<(p+i)->number<<endl;
}
long& PhoneBook::operator ()(char* a){
for (int i=0;i<n;i++){
if (strcmp((p+i)->name,a)==0)
return (p+i)->number;
}
}
void PhoneBook::setnumber(int a,long b){
(p+a)->number =b;
}
void PhoneBook::setname(int a,char* b){
strcpy((p+a)->name,b);
}
PhoneBook::PhoneBook(int a){
n=a;
p=(struct item*)calloc(n,sizeof(struct item));
}
PhoneBook::~PhoneBook(){
free(p);
}
//----------------------------------
int main(int argc, char* argv[])
{
PhoneBook a(10);
a(0)="hahaha0";
a(1)="hahaha1";
a(2)="hahaha2";
a(3)="hahaha3";
a(4)="hahaha4";
a(5)="hahaha5";
a(6)="hahaha6";
a(7)="hahaha7";
a(8)="hahaha8";
a(9)="hahaha9";
a("hahaha0")=12345;
a("hahaha1")=54321;
a("hahaha2")=1234;
a("hahaha3")=5431;
a("hahaha4")=1345;
a("hahaha5")=5321;
a("hahaha6")=1345;
a("hahaha7")=5421;
a("hahaha8")=13345;
a("hahaha9")=53421;
a.print();
cout<<"hahaha7 's number is "<<a["hahaha7"]<<endl;
cout<<"13345 's name is "<<a[13345]<<endl;
return 0;
}