const的问题,本人照超书上的为什么还有错

C语言 码拜 9年前 (2015-11-15) 690次浏览
//const的用法,试验
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
typedef struct Family Family;
struct Family
{
char name[20];
int age;
char father[20];
char mother[20];
};
bool siblings(Family const *pmember1,Family const *pmember2)
{
if(strcmp(pmember1->mother,pmember2->mother)==0)
return true;
else
return false;
}
int main (void)
{
Family member1={“one”,10,”gou”,”ma”};
Family member2={“tow”,12,”lang”,”ma”};
Family *pmember1=NULL;
Family *pmember2=NULL;
pmember1=&member1;
pmember2=&member2;
if(siblings(*pmember1,*pmember2))      //这里编译时出错,
printf(“\nzhe liangge dongwu shi yige mama.”);
return 0;
}
为什么编译时会出错。提示:
“cannot convert “”Family”” to “”const Family*”” for argument “”1″” to “”bool siblings(const Family*, const Family*)”””
函数加const,本人的本意是指针作为函数变元时,传递值时,不改变指针的值。
本人函数都是照抄书上的,别的是本人本人写出来的,就是为测试const的作用。但是出错了,为什么,该怎么改。
解决方案:40分
另外,按照你的要求“本人的本意是指针作为函数变元时,传递值时,不改变指针的值”,函数声明应该为:

bool siblings(Family* const pmember1, Family* const pmember2)
{
//……
}

原因是 Family const *pmember1 和 const  Family *pmember1 是一样的,都是保护指针指向的对象,Family* const pmember1才是保护指针本身


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明const的问题,本人照超书上的为什么还有错
喜欢 (0)
[1034331897@qq.com]
分享 (0)