【问题标题】:VS error C2664 (return string from a function) C++VS 错误 C2664(从函数返回字符串)C++
【发布时间】:2014-07-13 17:58:10
【问题描述】:

我确定这在网站上的某个地方得到了回答,但找不到它......我正在用 C++ 在 VS10 下编写。我正在写一个包含学生详细信息的课程。其中一位成员是

string studentName[30];

应该有一个函数可以根据请求返回这个字符串,这可以使用传统的 C 字符串和一个指针来完成,但是我想使用 C++ 字符串。

我的 get 函数如下所示:

string Student::getName()
{
    return studentName;
}

在编译时,我从 VS10 收到此错误:

错误 1 ​​错误 C2664: 'std::basic_string<_elem>::basic_string(const std::basic_string<_elem> &)' : 无法转换参数 1 从 'std::string [30]' 到 'const std::basic_string<_elem> &' f:\c++\hw1\hw1\hw3\hw3.cpp 56 1 HW3

我不确定这意味着什么。如果有人能澄清我将不胜感激。此外,在这些 get 函数中,通常会返回对字符串或实际文字值的引用(希望这是正确的术语)。

这样声明的学生姓名:

protected:
    string studentName[30];
    int  studentGrades[8];
    int  studentAge;
};

【问题讨论】:

  • 在您的班级中如何定义 studentName?
  • string studentName[30]; 是一个包含 30 个字符串的数组 - 这真的是您想要的吗?
  • studentName 被定义为不是字符串,而是由 30 个字符串组成的数组。您不能将字符串数组作为字符串传递。
  • 您只需将其声明为字符串 studentName;够了
  • @at0ma - 你是什么意思?

标签: c++ string return


【解决方案1】:

您将数据成员 studentName 定义为类型为 string[30]

string studentName[30];

同时函数getName有返回类型string

string Student::getName()

现在请回答编译器如何将string[30] 类型的对象转换为string 类型的对象?

我认为你的意思是以下

string Student::getName()
{
    return studentName;
}
protected:
    string studentName;
    int  studentGrades[8];
    int  studentAge;
};

那应该是 string studentName[30] 而不是 string studentName,因为我认为将学生的姓名存储在 30 个字符串中并没有什么意义,尽管在巴西可能有包含 30 个单词的名称。:)

【讨论】:

    【解决方案2】:

    studentNamestring*(数组 -> 指针),但您从函数返回 string。错误消息说明了一切。返回单个字符串或

    string* Student::getName()
    {
        return studentName;
    }
    

    【讨论】:

    • 问题出在成员声明中,而不是访问函数
    • 我冒昧地建议 string studentName; 是有意的。
    猜你喜欢
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多