当我尝试将一个函数作为参数传递给另一个函数时,我在C ++中遇到了这个奇怪的事情。这里的问题是它可以工作,但不能给我预期的结果。这是我的代码(msvc2013):
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <iostream>
typedef unsigned int uint32_t;
typedef unsigned char uint8_t;
using namespace std;
#include "stdafx.h"
uint32_t random_color()
{
uint8_t r = rand() % 255;
uint8_t g = rand() % 255;
uint8_t b = rand() % 255;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
return rgb;
}
void print_rgb(uint32_t(*color_generator)() = &random_color)
{
std::cout << color_generator << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < 5; i++)
{
srand(time(NULL));
print_rgb();
}
system("PAUSE");
return 0;
}
这段代码的目的更加复杂,但这只是一个最小的例子。
问题:虽然您看到了,但是srand(time(NULL));
为了rand()
更改值,它并没有!
有什么原因吗?我想念什么吗?
看起来您正在打印指向函数的指针的值,您的代码应为:
std::cout << color_generator() << std::endl;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句