C++草案标准(N3337)有关于指针转换的以下内容:
4.10指针转换
2类型的右值"指针CV
T",其中T是对象类型,可被转化为式的一个右值"指针CVvoid".一个"指针转换的结果CVT"发送给"指针CVvoid"指向类型对象T所在的存储位置的起始位置,就好像该对象是类型最派生的对象(1.8)T(即不是基类子对象).
和
4.12布尔转换
1算术,枚举,指针或指向成员类型的指针的右值可以转换为类型的右值
bool.零值,空指针值或空成员指针值转换为false; 任何其他值都转换为true
基于以上所述,将函数指针或指针转换int为a void*也是完全可以的bool.
但是,考虑到两者的选择,指针应该转换为哪一个?
然后,为什么指向函数的指针转换为a bool和指向int转换为void*?的指针?
程序:
#include <iostream>
using namespace std;
void foo(const void* ptr)
{
std::cout << "In foo(void*)" << std::endl;
}
void foo(bool b)
{
std::cout << "In foo(bool)" << std::endl;
}
void bar()
{
}
int main()
{
int i …Run Code Online (Sandbox Code Playgroud) #include <iostream>
int main(){
std::cout << main << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么在命令行中打印1?
我正在开发一个处理不同变量和函数地址的c ++程序.
当我在基于Linux的操作系统上编译我的程序时,包括main的所有函数都获得1的地址而不是像其他变量一样的8位六进制数,这在Windows中没有发生.
我写了这段小代码来解释这个问题
#include <iostream>
using namespace std;
void Function1();
void Function1()
{
}
int main()
{
int tmp;
void (*a) ()=&Function1;
cout<<a<<endl;
cout<<&Function1<<endl;
cout<<&main<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于所有3个cout呼叫,输出为1而不是虚拟地址.
我真的很感谢你的帮助
感谢Advance Aziz