C++的int初始化

来源:互联网 发布:linux vi常用命令 编辑:程序博客网 时间:2024/06/08 05:48
int MyInt(56);
std::cout<<"MyInt="<<MyInt<<std::endl;

int MySecondInt = int();        //int变量可以这样初始化
std::cout<<MySecondInt<<std::endl;

        //那么可不可以这样初始化呢? 
int MyThirdInt(int());    //error!!! now, this is exactly a function
        

所以 MyThirdInt 正确的写法是

int MyThirdInt(int())
{
        // other code...  
return 0;
}

既然MyThirdInt 是一个函数, 那么里面的参数是什么东东呢?

//我们在声明一个函数
int OtherInt()
{
return 33;
}

//再看三行代码
int (*pfunc)();
pfunc = OtherInt;
std::cout<<"MyThirdInt is: "<<MyThirdInt(pfunc)<<std::endl;

MyThirdInt 的参数是个函数指针,但是函数指针好像不能取出来....

所以这个特殊的Int变量需要重新定义,就像下面这样:

int MyThirdInt(int (*pInt)())
{
return pInt();
}

======================完整代码========================

// hellomsg.cpp : 
//

#include "stdafx.h"
#include <iostream>


int OtherInt()
{
return 33;
}

int MyThirdInt(int (*pInt)())
{

return pInt();
}

int _tmain(int argc, _TCHAR* argv[])
{
int MyInt(56);
std::cout<<"MyInt="<<MyInt<<std::endl;

int MySecondInt = int();
std::cout<<MySecondInt<<std::endl;

int (*pfunc)();
pfunc = OtherInt;
std::cout<<"MyThirdInt is: "<<MyThirdInt(pfunc)<<std::endl;

return 0;
}