C++中的函数调用面试题
最近参加了一个笔试,有这样一道题,大致如下。
问下面程序的四个函数中,哪些可以输出"Hello"?
Cpp代码
#include "iostream.h"
void S1(char *s)
{
s = "Hello";
}
void S2(char &*s)
{
s = "Hello";
}
void S3(char *&s)
{
s = "Hello";
}
void S4(char **s)
{
*s = "Hello";
}
void main()
{
char *str = "Bye";
S1(str);
cout<<str<<endl;
S2(str);
cout<<str<<endl;
S3(str);
cout<<str<<endl;
S4(&str);
cout<<str<<endl;
}
#include "iostream.h"
void S1(char *s)
{
s = "Hello";
}
void S2(char &*s)
{
s = "Hello";
}
void S3(char *&s)
{
s = "Hello";
}
void S4(char **s)
{
*s = "Hello";
}
void main()
{
char *str = "Bye";
S1(str);
cout<<str<<endl;
S2(str);
cout<<str<<endl;
S3(str);
cout<<str<<endl;
S4(&str);
cout<<str<<endl;
}
答案:S3和S4。
S1是传值调用。函数中的s作为形式参数,和实参str在内存中分别占据不同的空间,所以对型参s所作的赋值操作并没有应用到str上。
S2语法错误。编译器认为char &*s是指向引用的指针,并且认定此声明非法。
S3是传址调用。参数s是实参str的引用,两者在内存中对应相同的空间,所以对型参s所作的赋值操作同时也应用到str上。
S4虽然是传值调用,型参s和实参str也在内存中占据不同的空间,但是这两者都是指向字符指针的指针。他们所指向的字符指针地址相同,即str==*s,所以对字符指针的赋值在主函数中仍然有效。
- 最新评论
