c++ - 将 C 结构转换为 C++ 类

标签 c++ c class structure iostream

希望大家昨天与家人度过了愉快的时光!在出城探望家人时,我想我应该开始一些截止日期即将到来的项目,其中之一是将用 C 编写的代码转换为 C++,该代码使用结构数组来存储和修改数据使用对象数组的代码。虽然我最近熟悉了 C 编程语法,但这将是我的第一个 C++ 项目。我知道类应该与结构非常相似,但我对语法以及访问说明符的概念感到困惑。下面是我的原始 C 代码,以及要进行的更改的列表。任何有关如何开始的建议,包括此类工作的良好资源/教程,将不胜感激。预先感谢您的考虑!

修改:

  1. 将类中的所有数据声明为私有(private);
  2. 提供提供所有必需功能的方法(类函数) 让你的程序正常工作。特别是,声明一个构造函数方法 类(class)。
  3. 除了程序所需的方法外,还编写一个访问(\get")和 类中每个私有(private)数据成员的 mutator (\set") 函数。

我的代码:

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

//Function Prototypes
void insertFirstName(struct structureName[], char[], int);
void insertLastName(struct structureName[], char[], int);
void insertHomeNumber(struct structureName[], char[], int);
void insertCellNumber(struct structureName[], char[], int);
void printPhoneBook(struct structureName[], int);
int deleteFriend(struct structureName[], char[], int);
void showFriend(struct structureName[], char[], int);
void saveFile(FILE*, struct structureName[], int);
int loadFile(FILE*, struct structureName[]);

//Structure Declaration
typedef struct structureName{
   char *fName;  //member for First Name
   char *lName;  //member for Last Name
   char *hPhone; //member for Home Phone
   char *cPhone; //member for Cell Phone
} pbFriend;

int main(){

   int x = 0;
   int flag = 0; //returned in delete function to account for empty phonebook
   int entryCount = 0;//variable for count of entries
   int menuChoice = 0; //variable for switch statement
   int count = 0; //counter keeps track of entry numbers 
   char name[100] = {'\0'}; //place holder for entries
   pbFriend phoneBook[1000] = {'\0'}; //create instance
   char fileSave = '\0'; //variable for selection on file save query
   char fileLoad = '\0'; //variable for selection on file load query
   FILE *pbData; //file pointer

   do{
      //load file to phone book query
      printf("Welcome! Would you like to load a file into the phonebook? (y/n): ");
      scanf("%c",&fileLoad);
      getchar();

      if(fileLoad=='y'||fileLoad=='Y'){
         count = loadFile(pbData,phoneBook);
         printf("Success! File loaded!\n");
         entryCount = count;
      } //end if

      else{
         if(fileLoad!='n'&&fileLoad!='N'){
            printf("Invalid selection.\n");
         } //end if
      } //end else
   }while( fileLoad!='y'&&fileLoad!='Y'&&fileLoad!='n'&&fileLoad!='N');  //end do while

   do{
      //display menu                 
      printf("\nPhone Book Application\n");
      printf("1) Add friend\n");
      printf("2) Delete friend\n");
      printf("3) Show a friend\n");
      printf("4) Show phone book\n");
      printf("5) Quit\n");
      printf("What do you want to do?: ");
      scanf("%d",&menuChoice);
      getchar();
      switch(menuChoice){

      case 1:  //add friend case
         printf("\nFirst name: ");  //insert first name
         scanf("%s",name);
         getchar();
         //allocate memory
         phoneBook[count].fName = (char*)malloc(100*sizeof(char));

         //memory failed to allocate
         if(phoneBook[count].fName == NULL){
            printf("ERROR! Out of memory!");
         }//end if

         //memory allocated
         else{
            insertFirstName(phoneBook, name, count);   
         }//end else

         printf("Last name: "); //insert last name
         scanf("%s",name);
         getchar();

         //allocate memory
         phoneBook[count].lName = (char*)malloc(100*sizeof(char));

         //memory failed to allocate
         if(phoneBook[count].lName == NULL){
            printf("ERROR! Out of memory!");
         }//end if

         //memory allocated
         else{
            insertLastName(phoneBook, name, count);   
         }//end else

         printf("Phone number (home): "); //insert home number
         scanf("%s",name);
         getchar();

         //allocate memory
         phoneBook[count].hPhone = (char*)malloc(100*sizeof(char));

         //memory failed to allocate
         if(phoneBook[count].hPhone == NULL){
            printf("ERROR! Out of memory!");
         }//end if


         //memory allocated
         else{
            insertHomeNumber(phoneBook, name, count);   
         }//end else

         printf("Phone number (cell): "); //insert cell number
         scanf("%s",name);
         getchar();

         //allocate memory
         phoneBook[count].cPhone = (char*)malloc(100*sizeof(char));

         //memory failed to allocate
         if(phoneBook[count].cPhone == NULL){
            printf("ERROR! Out of memory!");
         }//end if

         //memory allocated
         else{
            insertCellNumber(phoneBook, name, count);   
         }//end else

         printf("Entry added to phone book!\n");
         printf("\n");
         count++;
         entryCount++;
         break;

      case 2:  //delete friend case
         printf("\nPlease provide a last name for entry deletion: ");
         scanf("%s",&name);
         getchar();
         strcat(name," "); //white space for string values
         flag = deleteFriend(phoneBook, name, count);

         //successful deletion
         if(flag == 1){
            printf("The entry has been deleted from the phonebook.\n");
            entryCount--;
         }//end if

         //no deletion
         else{
            printf("No deletion has been made.\n");
         } 
         printf("\n");
         break;

      case 3:  //show friend case
         printf("\n");
         printf("Please provide a last name: ");
         scanf("%s",&name);
         getchar();
         strcat(name," ");
         showFriend(phoneBook, name, count);
         printf("\n");
         break;

      case 4:  //show phone book case
         printf("\n");
         //empty phonebook
         if(entryCount == 0){
            printf("The phonebook is empty.\n");
         }//end if
         else{
            printPhoneBook(phoneBook, count);
         }//end else
         printf("\n");
         break;

      case 5:  //quit case
         do{
            printf("\nWould you like to save the phonebook to a file? (y/n): ");
            scanf("%c",&fileSave);
            getchar();

            switch(fileSave){
            case 'y': case 'Y': //save case
               saveFile(pbData,phoneBook,count);
               printf("Success! File saved!");
               break;       

            case 'n': case 'N': //exit without saving case 
               printf("Good bye!\n");
               break;

            default: //invalid case
               printf("Invalid selection.\n");
               break;
            } //end switch
         }while(fileSave!='y'&&fileSave!='Y'&&fileSave!='n'&&fileSave!='N'); //end do while
         break;

      default: //invalid case
         printf("Invalid menu choice.\n\n");
         break;
      }//end switch statement
   }while(menuChoice != 5); //end do while loop

   getch();
   return 0;
}//end main

//Function Definitions
//function to insert first name
void insertFirstName(pbFriend phoneBook[], char name[], int count){
   strcpy(phoneBook[count].fName, name);
   strcat(phoneBook[count].fName," ");  
}

//function to insert last name
void insertLastName(pbFriend phoneBook[], char name[], int count){
   strcpy(phoneBook[count].lName, name);
   strcat(phoneBook[count].lName," ");
}

//function to insert home phone number
void insertHomeNumber(pbFriend phoneBook[], char name[], int count){
   strcpy(phoneBook[count].hPhone, name);
   strcat(phoneBook[count].hPhone," ");
}

//function to insert cell phone number
void insertCellNumber(pbFriend phoneBook[], char name[], int count){
   strcpy(phoneBook[count].cPhone, name);
   strcat(phoneBook[count].cPhone," ");
}

//function to delete entry
int deleteFriend(pbFriend phoneBook[], char name[], int count){
   int x;
   int foundFlag = 0; //foundFlag for seeing if query is in structure
   char nullStr[30] = {'\0'}; //NULL string
   char name2[30] = {'\0'}; //string to store first name query
   //get first name to prevent multiple deletions due to same last name
   printf("Please provide the first name of the entry to be deleted: ");
   scanf("%s", &name2);
   getchar();
   strcat(name2," ");
   for(x=0;x<count;x++){
      if((strcmp(phoneBook[x].lName,name)==0)&&(strcmp(phoneBook[x].fName,name2)==0)){
         foundFlag = 1; //entry found, proceed with delete
         //free previously allocated memory
         free(phoneBook[x].fName);
         free(phoneBook[x].lName);
         free(phoneBook[x].hPhone);
         free(phoneBook[x].cPhone);
         //set free strings to NULL
         strcpy((phoneBook[x].fName), nullStr);
         strcpy((phoneBook[x].lName), nullStr);
         strcpy((phoneBook[x].hPhone), nullStr);
         strcpy((phoneBook[x].cPhone), nullStr);
      }//end if
   }//end for
   //entry not found
   if(foundFlag == 0){ 
      printf("\nSorry, there is nobody with that name in the phone book.\n");
   }//end if
   return foundFlag;
}//end function

//function to search entries by last name
void showFriend(pbFriend phoneBook[], char name[], int count){
   int x;
   int foundFlag = 0; //foundFlag for seeing if query is in structure
   printf("\n");
   for(x=0;x<count;x++){
      if(strcmp((phoneBook[x].lName), name) == 0){
         foundFlag = 1; //entry found, proceed with display
         printf("%s",phoneBook[x].fName);
         printf("%s",phoneBook[x].lName);
         printf("%s(home) ",phoneBook[x].hPhone);
         printf("%s(cell)",phoneBook[x].cPhone);
         printf("\n");
      }//end if   
   }//end for
   //entry not found
   if(foundFlag == 0){
      printf("Sorry, there is nobody with that name in the phone book.\n");
   }//end if                               
}//end function

//function to print phone book contents
void printPhoneBook(pbFriend phoneBook[], int count){
   int x;
   for(x=0;x<count;x++){
      //check to avoid NULL strings, which have been deleted
      if(strlen(phoneBook[x].fName) > 0){ 
         printf("%s", phoneBook[x].fName);
         printf("%s", phoneBook[x].lName);
         printf("%s(home) ", phoneBook[x].hPhone);
         printf("%s(cell)", phoneBook[x].cPhone);
         printf("\n");
      }//end if
   }//end for
}//end function

//function to save to a file
void saveFile(FILE *pbData, pbFriend phoneBook[], int count){
   char fileName[100] = {'\0'}; //string to store desired name to save file as
   int x = 0; //counter variable
   printf("Please enter the file name: ");
   scanf("%s",fileName);
   getchar();
   //open file
   pbData = fopen(fileName,"w");
   //file open fail case
   if(pbData == NULL){
      printf("ERROR! File not saved!\n");
      perror("The following error occurred"); //specifies i/o error
      getchar();
      exit(EXIT_FAILURE); //exit program with error
   } //end if
   //file open success case
   else{
      //write to file   
      for(x=0;x<count;x++){
         fprintf(pbData, "%s", phoneBook[x].fName);
         fprintf(pbData, "%s", phoneBook[x].lName);
         fprintf(pbData, "%s", phoneBook[x].hPhone);
         fprintf(pbData, "%s", phoneBook[x].cPhone);
      } //end for
      fclose(pbData);
   } //end else
}// end function

//function to load a file into the phone book
int loadFile(FILE *pbData, pbFriend phoneBook[]){
   char fileName[100] = {'\0'}; //variable to store name of file to load
   int count = 0; //counter variable
   char tabulaRasa[30] = {'\0'}; /*NULL string to clear garbage data from the
                                 last loop of the feof() condition when loading 
                                 files*/
   printf("Please enter the name of the file you wish to load: ");
   scanf("%s",fileName);
   getchar();
   //open file
   pbData = fopen(fileName,"r");
   //file open fail case
   if(pbData == NULL){
      printf("ERROR! Unable to load file!\n");
      perror("The following error occurred"); //specifies i/o error
      getchar();
      exit(EXIT_FAILURE); //exit program with error
   } //end nested if
   //file open success case
   else{
      //allocate memory to store data from a file
      while(!feof(pbData)){
         phoneBook[count].fName = (char*)malloc(100*sizeof(char));
         if(phoneBook[count].fName == NULL){
            printf("ERROR! Out of memory!");
         } //end double nested if
         phoneBook[count].lName = (char*)malloc(100*sizeof(char));
         if(phoneBook[count].lName == NULL){
            printf("ERROR! Out of memory!");
         } //end double nested if
         phoneBook[count].hPhone = (char*)malloc(100*sizeof(char));
         if(phoneBook[count].hPhone == NULL){
            printf("ERROR! Out of memory!");
         } //end double nested if
         phoneBook[count].cPhone = (char*)malloc(100*sizeof(char));
         if(phoneBook[count].cPhone == NULL){
            printf("ERROR! Out of memory!");
         } //end double nested if
         //load from file
         fscanf(pbData,"%s",phoneBook[count].fName);
         strcat(phoneBook[count].fName," "); 
         fscanf(pbData,"%s",phoneBook[count].lName);                         
         strcat(phoneBook[count].lName," ");
         fscanf(pbData,"%s",phoneBook[count].hPhone);
         strcat(phoneBook[count].hPhone," ");
         fscanf(pbData,"%s",phoneBook[count].cPhone);
         strcat(phoneBook[count].cPhone," ");
         count++; //show that entry/entries have been made from file
      }//end while loop
      //free memory of last entry (junk data from feof() condition)
      free(phoneBook[count-1].fName);
      free(phoneBook[count-1].lName);
      free(phoneBook[count-1].hPhone);
      free(phoneBook[count-1].cPhone);
      //set newly free strings to NULL
      strcpy((phoneBook[count-1].fName), tabulaRasa);
      strcpy((phoneBook[count-1].lName), tabulaRasa);
      strcpy((phoneBook[count-1].hPhone), tabulaRasa);
      strcpy((phoneBook[count-1].cPhone), tabulaRasa);
      count--;
   } //end nested else
   fclose(pbData);
   return(count); //show that phone book is not empty
} //end if

最佳答案

开始手头任务的一个绝妙方法是查看 C++ Getting Started 中的一些项目。页。

关于c++ - 将 C 结构转换为 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13535302/

相关文章:

java - 如何告诉 Java 接口(interface)实现了 Comparable?

C++ 错误 : 'No suitable conversion from [class name] to "int"'

C++删除段错误

c++ - 编译时PCAP程序错误

c++ - 在模板类中声明与 friend 相同的模板类?

c - 这两行有什么区别?

c - 为什么这个阻塞套接字读取返回零并且没有错误?

java - "form"在同一个文件中声明新类好吗?

c++ - 如何从 C++ 程序内部测量内存使用情况?

c++ - 运算符 << 和继承