将字符串指针传递给 C++ 中的结构 [英] Passing a string pointer to a struct in C++

查看:63
本文介绍了将字符串指针传递给 C++ 中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to pass various strings into members of a Struct via pointer but I am doing something fundamentally incorrect. What I think is that it doesn't need to be dereferenced. The process below works for other types of data such as int or char. For example:

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 时出现错误:

I get an error when I try to compile the following algorithm to initialize a Course:

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

    }

错误:

错误:无法将参数 '2' 的 'const char*' 转换为 'std::string* {aka std::basic_string<char>*}' 到 'void c_Init(Course*, std::字符串*, ..

推荐答案

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

You're actually defining, for example, an array of 15 strings in the location field. Either use regular strings; 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;

这篇关于将字符串指针传递给 C++ 中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆