我敢肯定这在网站上的某个地方得到了回答,但找不到它...我正在用 C++ 在 VS10 下编写。我正在写一个包含学生详细信息的类(class)。其中一名成员是
string studentName[30];
应该有一个根据请求返回此字符串的函数,这可以使用传统的 C 字符串和指针来完成,但我想使用 C++ 字符串。
我的 get 函数如下所示:
string Student::getName()
{
return studentName;
}
在编译时,我从 VS10 得到这个错误:
Error 1 error C2664: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'std::string [30]' to 'const std::basic_string<_Elem,_Traits,_Ax> &' f:\c++\hw1\hw1\hw3\hw3.cpp 56 1 HW3
我不确定这是什么意思。如果有人能澄清我将不胜感激。此外,在这些 get 函数中,返回字符串或实际文字值的引用很常见(希望这是正确的行话)。
如此声明的 StudentName:
protected:
string studentName[30];
int studentGrades[8];
int studentAge;
};
最佳答案
您将数据成员 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 个单词的名字。:)
关于c++ - VS 错误 C2664(从函数返回字符串)C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23845075/