C to C ++:将结构转换为类

时间:2012-11-26 23:05:24

标签: c++ c class struct

所以,这可能有点大,可能是凌乱和不正确的(它真的是初学者)。我只是在学习C,而我需要做的部分工作包括将这个程序转换为C ++程序。我需要做的主要是用类替换所有结构,并且代码中使用的所有函数都是类函数(成员?如果我记得......)

我对很多基础知识有很好的把握,但这个概念只是“修改”代码。我没有看到如何通过切换到类来“修改”我以前的工作。就像我一样,我觉得程序需要重写才能使用类。也许我错过了这里的简约。我不希望有人为我做这项工作,我只是想知道是否有一种简单的方法可以将我的结构格式化为类。

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

//Struct for friend array pointers.
typedef struct friendstruct{
        char *firstname;
        char *lastname;
        char *homephone;
        char *cellphone;
} frnd;
//Buffer for use in storing in the main program.
typedef struct bufferstruct{
        char firstname[20];
        char lastname[20];
        char homephone[20];
        char cellphone[20];
} frndbuff;
//Add friend function.
void addfriend(frnd friendarray[], frndbuff newfrnd, int count, int opened){
     friendarray[count].firstname = malloc(sizeof(newfrnd.firstname));  //Assign memory before copying string.
     friendarray[count].lastname = malloc(sizeof(newfrnd.lastname));
     friendarray[count].homephone = malloc(sizeof(newfrnd.homephone));
     friendarray[count].cellphone = malloc(sizeof(newfrnd.cellphone));
     strcpy(friendarray[count].firstname, newfrnd.firstname);
     //printf("%s", friendarray[count].firstname);
     //printf("%s", newfrnd.firstname);
     strcpy(friendarray[count].lastname, newfrnd.lastname);
     strcpy(friendarray[count].homephone, newfrnd.homephone);
     strcpy(friendarray[count].cellphone, newfrnd.cellphone);
     //friendarray[count].lastname = newfrnd.lastname;
     //friendarray[count].homephone = newfrnd.homephone;
     //friendarray[count].cellphone = newfrnd.cellphone;

     if(opened==0){
     printf("\nA new friend has been added to the phonebook.");
     }
}
//Deleteing friends.
int deletefriend(frnd friendarray[], frndbuff newfrnd, int count){
     int n = 0;
     int success = 0;
     while(n<count){
           if(strcmp(newfrnd.lastname,friendarray[n].lastname)==0){ //Comparing strings.
                 while(n<count-1){
                                 strcpy(friendarray[n].firstname, friendarray[n+1].firstname);
                                 strcpy(friendarray[n].lastname, friendarray[n+1].lastname);
                                 strcpy(friendarray[n].homephone, friendarray[n+1].homephone);//Removes previously used position.
                                 strcpy(friendarray[n].cellphone, friendarray[n+1].cellphone);
                                 //friendarray[n].lastname = friendarray[n+1].lastname;
                                 //friendarray[n].homephone = friendarray[n+1].homephone;
                                 //friendarray[n].cellphone = friendarray[n+1].cellphone;
                                 n++;
                 }
           success = 1;
           count = count - 1;
           break;
           }
           n++;
     }      
           if(success==1){
           printf("\nThe entry for %s has been removed from the phonebook.", newfrnd.lastname);
           }else{
           printf("\nThat entry was not found");
           }
           //printf("%i", count);
return count;
}
//Show friend by last namme. Identical to delete friend, without removal.
void showfriend(frnd friendarray[], frndbuff newfrnd, int count){
     int n = 0;
     int success = 0;
     while(n<count){
           if(strcmp(newfrnd.lastname, friendarray[n].lastname)==0){
           printf("\n\n%s %s %s (home) %s (cell)\n", friendarray[n].firstname, friendarray[n].lastname, friendarray[n].homephone, friendarray[n].cellphone);                      
           success = 1;
           break;
           }
     n++;
     }

           if(success==0){
           printf("\nThat entry was not found");
           }
}
//DIsplays entire phonebook.
void phonebook(frnd friendarray[], int count){
     int n = 0;
     //printf("%i", count); Used in debugging.
     while(n<count){
     printf("\n%s %s %s (home) %s (cell)\n", friendarray[n].firstname, friendarray[n].lastname, friendarray[n].homephone, friendarray[n].cellphone);
     n++;
     }
}
//Find friend based on last name.
void searchfriend(frnd friendarray[], frndbuff newfrnd, int count){
     int n = 0;
     int success = 0;
     while(n<count){
           if(strcmp(newfrnd.lastname, friendarray[n].lastname)==0){
           printf("\n\n%s %s %s (home) %s (cell)\n", friendarray[n].firstname, friendarray[n].lastname, friendarray[n].homephone, friendarray[n].cellphone); 
           success = 1;                     
           }
     n++;
     }

           if(success==0){
           printf("\nThat entry was not found");
           }
}                        

int main(){
    int option, option2;
    frndbuff currentfriend;
    frnd friendarray[50];
    int count = 0;
    int filecount = 0;
    int opened = 0;
    //Phonebook load previous to main loop.
    printf("\nDo you have a previously saved phonebook you'd like to load?\n1) Yes\n2) No\n");
    printf("\nChoose an option : ");
    scanf("%i", &option2);
        if(option2==1){

                  FILE *fileopen;
                  fileopen = fopen("phonebook.dat", "r"); //File open for reading.
                  if (fileopen != NULL){
                               filecount = 0;
                               opened = 1;
                               printf("\nYour previous phonebook has been loaded : ");
                               while(fscanf(fileopen, "%s %s %s (home) %s (work)\n",&currentfriend.firstname, &currentfriend.lastname, &currentfriend.homephone, &currentfriend.cellphone)==4){
                                                      printf("\n%s %s %s (home) %s (work)\n",currentfriend.firstname, currentfriend.lastname, currentfriend.homephone, currentfriend.cellphone);
                                                      addfriend(friendarray, currentfriend, filecount, opened);
                                                      filecount++;
                               }
                               count = filecount;
                  }else if(fileopen == NULL){
                               printf("\nA previous phonebook could not be found.");
                  }
    }

while(1==1){



    opened = 0;                
    printf("\n\nPhone Book Application\n1) Add Friend\n2) Delete Friend\n3) Show a Friend\n4) Show phone book\n5) Search by last name\n6) Quit\n");    
    printf("\n\nWhat option would you like to choose : ");
    scanf("%i", &option);  
    //Option ensuring.
    if(option<1 || option>6){
                printf("\nYou did not enter a valid option, please try again.");
                option = 6;
    }

    if(option==1){
                  printf("\nFirst Name : ");
                  scanf("%s", &currentfriend.firstname);
                  printf("\nLast Name : ");
                  scanf("%s", &currentfriend.lastname);
                  printf("\nHome Phone : ");
                  scanf("%s", &currentfriend.homephone);
                  printf("\nCell Phone : ");
                  scanf("%s", &currentfriend.cellphone);
                  //printf("%s", currentfriend.firstname); Debugging.
                  addfriend(friendarray, currentfriend, count, opened);


                  count++;
                  //printf("%i", count); Debugging.
                  //All options call the previously made functions and pass the buffer.
    }else if(option==2){
                  printf("\nEnter the last name of the friend you'd like to delete : ");
                  scanf("%s", &currentfriend.lastname);
                  count = deletefriend(friendarray, currentfriend, count);
    }else if(option==3){
                  printf("\nEnter the last name of the friend you'd like to view : ");
                  scanf("%s", &currentfriend.lastname);
                  showfriend(friendarray, currentfriend, count);
    }else if(option==4){
                  phonebook(friendarray, count);
    }else if(option==5){
                  printf("\nEnter the last name you'd like to search : ");
                  scanf("%s", &currentfriend.lastname);
                  searchfriend(friendarray, currentfriend, count);
    }else if(option==6){
                  option2 = 0;
                  printf("\nWould you like to save your phonebook to a file?\n1) Yes\n2) No");
                  printf("\n Choose an option : ");
                  scanf("%i", &option2);
                  if(option2==1){
                                 filecount = 0;
                                 FILE *filesave;
                                 filesave = fopen("phonebook.dat", "w"); //File open for writing.
                                 while(filecount<count){
                                 //File written in the same method it is read.
                                 fprintf(filesave, "%s %s %s (home) %s (work)\n",friendarray[filecount].firstname, friendarray[filecount].lastname, friendarray[filecount].homephone, friendarray[filecount].cellphone);
                                 filecount++;
                                 }
                  }
                  printf("\nThank you for using this Phone Book Application!");
                  break;
    }
}
//Files closed.
fclose(fileopen);
fclose(filesave);
getch();
return 0;
} 

3 个答案:

答案 0 :(得分:2)

与C ++的主要区别在于使用 std::string 而不是原始字符数组。然后,您不使用mallocfree。您只需让std::string负责内存管理。

同样,您可以使用 std::vector 来存储朋友。

你也可以用C ++ iostreams i / o替换i / o,这样更简单,更安全。

Bjarne Stroustrup写了一篇介绍 how to transform a little C program into C++ 的小文章(“学习标准C ++作为新语言”,C / C ++用户期刊1999年5月43-54页)。

你只需要“忘掉”一些C做事方式,并采用更多C ++的方式。 : - )

答案 1 :(得分:2)

首先,在C ++中,结构和类之间的差别很小。

一个类是一个结构,其中字段/方法默认是私有的。

struct Foo {
    //Content here
};

相同
class Foo {
public:
    //Content here
};

但是,当然,这并没有使用C ++类的所有“好东西”。

  1. typedef struct X { ... } Y;struct X { ... }替换struct Y { ... };。在C ++中使用typedef并没有多大意义。

  2. 如果您不是指“将代码转换为类”而是“使用标准C ++类而不是C功能”,则将char name[N]替换为std::string name;,替换{{ 1}} by Type[](不要忘记通过引用将向量传递给函数,如果你不知道通过引用传递什么 - 学习它,这是一个重要的概念)。

  3. 如果您使用C ++标准字符串,则不再需要std::vector<Type> / malloc / free。而不是strcpy只使用strcpy(a, b);

  4. 如果您正确地遵循这些提示,我相信您的代码将大大简化。然后,你会发现你的一些功能变得没必要了。例如,a = b;可能会被addfriend替换。

答案 2 :(得分:0)

  • 在现有答案中建议切换到std::stringstd::vector<>
    • std::string具有值语义,这意味着您只需使用==来比较字符串,并=分配给字符串。
  • 你不需要朋友 - buff类或结构......只需在任何地方使用朋友类。
  • 您可能希望向其添加构造函数,以便您可以使用简单的Friend(firstname, lastname, homephone, cellphone)创建实例,而无需每次都明确分配给每个成员(提示 - 使用“初始化列表”)。
    • 因为std::string具有值语义(与指针类似),所以您不需要创建复制构造函数或析构函数来复制或清理字符串使用的内存...它将一切正常。
  • 您可以使用标准算法来执行诸如擦除vector中的元素...所有容易用Google搜索或在堆栈溢出中找到的内容。
  • iostreams意味着您可以编写代码来输出变量而无需指定变量的类型(因为您必须使用printf()) - 编译器会自动找到适当的代码。您需要#include <iostream>然后std::cout << variable << "string literals\n";等。
    • 您不需要使用std::endlstd::flush,除非您希望输出立即显示,即使您没有等待输入 - 只需\n通常是正确的选择许多C ++书籍/教程等显示endl