2011-01-24 46 views
0
#include </usr/include/boost/optional.hpp> 
#include <iostream> 
using namespace std; 


boost::optional<int> test_func(int i) 
{  
    if(i) 
    return boost::optional<int>(1234); 
    else 
    return boost::optional<int>(); 
    return (i); 
} 

int main() 
{ 
    int i; 
    test_func(1234); 
    std::cout<< test_func(i) << endl; 
    return 0; 
} 

任何机构请告诉我我是我得到我的价值为0,我想要做的是我想输入后打印“我”的值“if”条件&也在“其他”部分。需要帮助C++ boost ::可选

请做要紧,请参阅我的任何修改的 感谢 Arun.D

帮助是极大的赞赏..谢谢提前

+1

能否请你格式化你的源代码,使其可读? –

+1

@丹,已经这样做了,只是等待某人批准编辑:) –

回答

3

您还没有初始化i。这个程序的行为是未定义的。明确地将其设置为非零值。

4

int i尚未明确初始化。如果i == 0则返回nil(默认boost :: optional),当你打印时你会得到0.

2

在main()中你还没有初始化i。而在test_func(),你永远不会达到return (i);

+0

if(i) retun boost ::可选(1234);但为什么至少这没有回报价值。我想要做的是我想模拟Boost :: Optional –

+0

的功能,如果(i) retun boost ::可选(1234);但为什么至少这没有回报价值。我想要做的是我想模拟Boost的操作:: Optional pls help –

1

其他已经评论:你正在使用我没有初始化,它是默认初始化为0. 但也许你想知道为什么你看不到1234:这是因为你丢弃返回值(硬编码提升::可选(1234))。 也许你的意思是写

std::cout << *test_func(1234) << endl; // by using operator* you are not discarding the return value any more 
std::cout<< test_func(i) << endl; 

阅读the documentation,并期待在examples了解更多信息

+0

std :: cout << test_func(1234)<< endl;现在这个打印只有1,你可以修改我上面的代码片段..这将是很大的帮助,谢谢一吨。 –

+0

@阿伦达巴尔:现在应该更清楚了。 – Francesco

0

除了未初始化i并没有达到return i;其他已经提到:

您打印boost::optionalbool conversion 。如果可选包含值,则打印1,如果可选不包含值,则打印0

我想你的意思是这样的:

boost::optional<int> result(test_func(i)); 
if (result) 
{ 
    std::cout << *result; 
} 
else 
{ 
    std::cout << "*not set*"; 
} 

,而不是

std::cout << test_func(i);