【问题标题】:Passing a string pointer to a struct in C++ (cont)将字符串指针传递给 C++ 中的结构(续)
【发布时间】:2014-02-11 05:49:59
【问题描述】:

这是这个问题的延续,一些好心人已经帮助了我:Passing a string pointer to a struct in C++

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

typedef struct Course{
    string location;
    string course;
    string title;
    string prof;
    string focus;
    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* or argument ‘2’ to ‘void c_Init

【问题讨论】:

    标签: c++ string pointers struct


    【解决方案1】:

    改变

    void c_Init(课程 *d, 字符串 *location, ... ){ c_SetLocation(d, &location); . . .

    }
    

    void c_Init(课程 *d, 字符串位置, ... ){ c_SetLocation(d, 位置); . . .

    }
    

    没有理由传递位置指针。

    【讨论】:

    • 当您的建议(以及我最初认为的正确方法)没有奏效时,我只是出于绝望才这样做。遗憾的是,我仍然收到同样的错误。
    • 由于您没有修改位置(我假设)将参数设置为字符串 const &location
    • 我正在修改它。好吧,还有一个额外的功能可以做到这一点。但不管你的建议是否正确,谢谢。
    【解决方案2】:
    *location; //this is de-referencing
    &location; //this is address of a variable (pointer to a variable)
    

    因此,为了将字符串传递给 c_SetLocation,您应该取消对它的引用:

     void c_Init(Course *d, string *location, ... ){
        c_SetLocation(d, *location);
        . . .
    }
    

    【讨论】:

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