【发布时间】:2015-11-22 19:31:32
【问题描述】:
1 #include <iostream>
2
3 namespace primerlib {
4 void compute() { std::cout << "primerlib::print()" << std:: endl; }
5 void compute(const void *p) { std::cout << "primerlib::print(const void *p)" << std:: endl; }
6 }
7
8 //using primerlib::compute;
9 //using namespace primerlib;
10 void compute(int a) { std::cout << "::compute(int)" << std:: endl; }
11 void compute(double d, double dd=3.4) { std::cout << "primerlib::compute(d, d)" << std:: endl; }
12 void compute(char* p, char* p1 = 0) { std::cout << "primerlib::compute(char*, char*)" << std:: endl; }
13
14 int main(void)
15 {
16 using primerlib::compute;
17 //using namespace primerlib;
18 compute(0);
19 return 0;
20 }
输出:
primerlib::print(const void *p)
我的问题是为什么它没有调用 global compute(int) one ?如果我在第 17 行使用 using 指令,它将调用 compute(int) 之一。非常感谢您的帮助。
【问题讨论】:
-
这说明了为什么不应该以这种方式使用函数重载。不要仅仅因为您可以!而给程序中的每个函数都赋予相同的名称
-
无论如何,
using并不总是指命名空间;它也可以指个别功能。这就是这个程序所做的。有人告诉它在primerlib命名空间中使用compute函数。我不确定我可以解释为什么当您取消注释第 17 行时它的行为会有所不同。0仍然是一个 const void 指针。 -
这只是一个示例代码,用于理解命名空间、使用声明/指令和函数重载。
-
您是否对如何使用
0调用void(const void*)感到困惑?0代表一个空指针。 -
不,我很困惑为什么不调用全局计算(int)。
标签: c++