// Function displays course information
// instructor defaults to Staff
// enrollment defualts to 30
// main() demonstrates function can be called three ways
#include<iostream>
using namespace std;
int main()
{
void displayCourseInfo(char, char* = "Staff", int = 30);
displayCourseInfo("ENG101");
displayCourseInfo("PSY151", "Bossert");
displayCourseInfo("CIS200", "Edwards", 24);
return 0;
}
void displayCourseInfo(char course, char* instructor, int enrollment)
{ cout << course << " taught by " << instructor <<
" enrollment " << enrollment << endl;
}
当我尝试运行此代码时,我得到了 this错误消息。它说我不能将* const char转换为char。 感谢您的时间和帮助。
答案 0 :(得分:2)
C ++中的字符串文字(与C相反)具有常量字符数组的类型。例如,字符串文字"Staff"
的类型为const char [6]
。
在表达式中使用具有罕见异常的数组指示符将转换为指向其第一个元素的指针。因此,用作参数的字符串文字"Staff"
将转换为类型const char *
的指针。
当您尝试将字符串文字作为参数传递时,函数displayCourseInfo
的第一个参数被声明为具有类型char
。
有效程序可以按以下方式查看
// Function displays course information
// instructor defaults to Staff
// enrollment defualts to 30
// main() demonstrates function can be called three ways
#include<iostream>
using namespace std;
int main()
{
void displayCourseInfo( const char *, const char * = "Staff", int = 30 );
displayCourseInfo("ENG101");
displayCourseInfo("PSY151", "Bossert");
displayCourseInfo("CIS200", "Edwards", 24);
return 0;
}
void displayCourseInfo( const char *course, const char *instructor, int enrollment)
{
cout << course << " taught by " << instructor
<< " enrollment " << enrollment << endl;
}
它的输出是
ENG101 taught by Staff enrollment 30
PSY151 taught by Bossert enrollment 30
CIS200 taught by Edwards enrollment 24
答案 1 :(得分:1)
这是因为&#34;在引号中测试&#34;默认情况下为const char*
声明中声明为const
的值无法更改
您不能将const
变量传递给采用非const参数的函数。
您可以创建函数的参数const
:
#include<iostream>
using namespace std;
void displayCourseInfo(const char *);
void displayCourseInfo(const char *, const char *);
void displayCourseInfo(const char *, const char *, const int);
int main() {
displayCourseInfo("ENG101");
displayCourseInfo("PSY151", "Bossert");
displayCourseInfo("CIS200", "Edwards", 24);
return 0;
}
void displayCourseInfo(const char *course, const char *instructor) {
cout << course << " taught by " << instructor <<
" enrollment " << 30 << endl;
}
void displayCourseInfo(const char *course) {
cout << course << " taught by " << "Staff" <<
" enrollment " << 30 << endl;
}
void displayCourseInfo(const char *course, const char *instructor, const int enrollment) {
cout << course << " taught by " << instructor <<
" enrollment " << enrollment << endl;
}