1、面试问题
编写程序判断—个变量是不是指针。
2、指针的判别
拾遗
C++中仍然支持C语言中的可变参数函数
C++编译器的匹配调用优先级
1. 重载函数
2. 函数模板
3. 变参函数
思路
将变量分为两类:指针 vs 非指针
编写函数:指针变量调用时返回true ,非指针变量调用时返回false
函数模板与变参函数的化学反应
template
<typename T>
bool IsPtr(T* v) // match pointer
{
return true;
}
bool IsPtr(...) // match non-pointer
{
return false;
}
编程实验
指针判断 test.cpp
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
}
virtual ~Test()
{
}
};
template
<typename T>
bool IsPtr(T* v) // match pointer
{
return true;
}
bool IsPtr(...) // match non-pointer
{
return false;
}
int main(int argc, char *argv[])
{
int i = 0;
int* p = &i;
cout << "p is a pointer: " << IsPtr(p) << endl; // 1
cout << "i is a pointer: " << IsPtr(i) << endl; // 0
Test t;
Test* pt = &t;
cout << "pt is a pointer: " << IsPtr(pt) << endl; // 1
/*
* error: cannot pass object of non-trivial type 'Test' through variadic function; call will abort at runtime
*/
cout << "t is a pointer: " << IsPtr(t) << endl; // 0 或 程序崩溃
return 0;
}
存在的缺陷: 变参函数无法解析对象参数,可能造成程序崩溃!
进—步的挑战: 如何让编译器精确匹配函数,但不进行实际的调用?
完美解决方案:
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
}
virtual ~Test()
{
}
};
template
<typename T>
char IsPtr(T* v) // match pointer
{
return 'd';
}
int IsPtr(...) // match non-pointer
{
return 0;
}
#define ISPTR(p) (sizeof(IsPtr(p)) == sizeof(char)) // 通过使用sizeof在编译期间就能确定ISPTR(p)的值
int main(int argc, char *argv[])
{
int i = 0;
int* p = &i;
cout << "p is a pointer: " << ISPTR(p) << endl; // true
cout << "i is a pointer: " << ISPTR(i) << endl; // false
Test t;
Test* pt = &t;
cout << "pt is a pointer: " << ISPTR(pt) << endl; // true
cout << "t is a pointer: " << ISPTR(t) << endl; // false
return 0;
}
3、小结
C++中依然支持变参函数
变参函数无法很好的处理对象参数
利用函数模板和变参函数能够判断指针变量
————————————————
版权声明:本文为CSDN博主「洋葱汪」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39654127/article/details/79869243
C++--面试题:判断—个变量是不是指针
最新推荐文章于 2022-05-01 15:42:04 发布