【问题标题】:C to C++ : Converting structs to classes [closed]C 到 C++:将结构转换为类 [关闭]
【发布时间】:2012-11-26 23:05:24
【问题描述】:

所以,这可能有点大,而且可能是混乱和不正确的(它真的是初学者)。我只是在学习 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;
} 

【问题讨论】:

  • 您只是在学习 C,并且已经将它与 C++ 混合使用了吗?
  • 嗯,结构基本上是类,只是具有默认的“公共”可见性。您真正需要做的就是将typedef struct foostruct{...} foo; 更改为class foo {public: ...}
  • 您有什么要求?您是否只是想将其从 .c 移至 .cpp?您是否尝试将其重写为 C++ 惯用语?面向对象?只需将“struct”替换为“class”即可?
  • 是的,如果您想将其转换为正确的 C++,则此代码不可挽救。你将不得不重写。在这种情况下我不会打扰。
  • 其实是在课堂上。我们正在非常突然地切换到 C++。我们没有学习任何 C++ 基础知识(幸运的是,我知道一些),我们希望只学习它并使其使用类而不是结构。是的,主要焦点是将结构转换为类。我应该添加一个要求,如果类变量是私有的,并且函数现在是类中的成员。

标签: c++ c class struct


【解决方案1】:

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

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

您也可以将 i/o 替换为 C++ iostreams i/o,这样更简单、更安全。

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

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

【讨论】:

  • 谢谢。我认为需要对字符串进行一些更改才能使它变得漂亮。
  • iostreams i/o 真的比 C 的 I/O 简单吗?个人觉得C中I/O的格式化比C++简单。
  • @ThomasMatthews:我倾向于同意你重新格式化。还有很多。但是对于simple i/o iostreams 简化了事情,特别是输入任意长的文本行(通过std::getline)。而且更安全。调用未定义行为的方法较少。 :-)
【解决方案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;,将 Type[] 替换为 @987654329 @ (不要忘记通过引用将向量传递给函数,如果您不知道什么是引用传递 - 学习它,这是一个重要的概念)。

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

如果您正确地遵循这些提示,我相信您的代码将会大大简化。然后,您会发现您的某些功能变得不必要了。例如,addfriend 可能会被 vector.push_back 替换。

【讨论】:

  • 我有点同意。我想我将从基础开始,使用普通的 C++ 标准将其从 C 转录为 C++,并应用人们帮助我的东西。谢谢!
  • 您必须记住,OP 询问的是如何将 C 结构转换为 C++ 类,而不是 C++ 结构转换为 C++ 类。
【解决方案3】:
  • 在现有答案中强烈建议切换到 std::stringstd::vector&lt;&gt;
    • std::string 具有值语义,这意味着您可以简单地使用 == 来比较字符串,并使用 = 来分配字符串。
  • 您不需要friend-buff 类或结构...只需在任何地方使用friend 类即可。
  • 您可能希望向其中添加一个构造函数,这样您就可以使用简单的Friend(firstname, lastname, homephone, cellphone) 创建一个实例,而无需每次都显式地分配给这些成员中的每一个(提示 - 使用“初始化列表”)。
    • 因为std::string 具有值语义(不同于类似指针),您不需要创建复制构造函数或析构函数来复制或清理字符串使用的内存...工作。
  • 您可以使用标准算法来执行诸如从 vector... 中删除元素之类的操作,所有这些都可以轻松通过 Google 搜索或在 stackoverflow 上找到。
  • iostreams 意味着您可以编写代码以输出变量而无需指定变量的类型(您必须使用 printf())- 编译器会自动找到适当的代码。你需要#include &lt;iostream&gt; 然后std::cout &lt;&lt; variable &lt;&lt; "string literals\n"; 等等。
    • 您不需要使用std::endlstd::flush,除非您希望输出立即出现,即使您不等待输入 - 只需\n 通常是正确的选择,尽管许多 C++ 书籍/教程等. 显示endl

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2020-04-16
    • 2021-03-10
    • 1970-01-01
    相关资源
    最近更新 更多