【问题标题】:Passing a string pointer to a struct in C++将字符串指针传递给 C++ 中的结构
【发布时间】:2014-03-08 18:06:02
【问题描述】:

我试图通过pointer 将各种strings 传递给Struct 的成员,但我做的事情根本不正确。我认为它不需要被取消引用。以下过程适用于其他类型的数据,例如 intchar。例如:

typedef struct Course {
    string location[15];
    string course[20];
    string title[40];
    string prof[40];
    string focus[10];
    int credit;
    int CRN;
    int section;
} Course;


void c_SetLocation(Course *d, string location){
    d->location = location;
    . . .
}

当我尝试编译以下算法来初始化 Course 时出现错误:

    void c_Init(Course *d, string &location, ... ){
        c_SetLocation(d, location[]);
        . . .

    }

错误:

error: cannot convert ‘const char*’ to ‘std::string* {aka std::basic_string<char>*}’ for argument ‘2’ to ‘void c_Init(Course*, std::string*, ..

【问题讨论】:

    标签: c++ string pointers struct


    【解决方案1】:

    例如,您实际上是在 location 字段中定义了一个包含 15 个字符串的数组。要么使用常规字符串; e. g.:

    typedef struct Course {
        string location;
        string course;
        string title;
        string prof;
        string focus;
        int credit;
        int CRN;
        int section;
    } Course;
    

    或使用字符数组:

    typedef struct Course {
        char location[15];
        char course[20];
        char title[40];
        char prof[40];
        char focus[10];
        int credit;
        int CRN;
        int section;
    } Course;
    

    【讨论】:

      【解决方案2】:

      当您声明 char a[10] 时,您将创建一个包含 10 个字符的数组。当您声明std::string 时,您正在创建一个可以增长到任意大小的字符串。当您声明 std::string[15] 时,您将创建一个包含 15 个字符串的数组,该数组可以增长到任意大小。

      你的结构应该是这样的:

      typedef struct Course {
          std::string location;
          std::string course;
          std::string title;
          std::string prof;
          std::string focus;
          int credit;
          int CRN;
          int section;
      } Course;
      

      【讨论】:

        【解决方案3】:

        string location[15] 表示您要创建 string 的 15 个实例,每个实例都可以有任意长度的文本。

        您需要分配以下 15 个字符串之一,而不是 d->locationd->location[0] = locationd->location[1] = location 等。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-10-09
          • 2021-04-29
          • 1970-01-01
          • 2012-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多