如何访问类中的全局函数,该类具有与全局函数相同的函数签名
How access global function in class which is having same function signature as global function?
以下是我的场景:
file.h此文件包含两个带有外部的函数
extern int add(int a, int b);
extern int sub(int a, int b);
file.cpp以上函数的实现。
int add(int a, int b)
{
return 20;
}
int sun(int a, int b)
{
return 20;
}
test.h这是一个类测试,其中两个成员函数具有与文件.h 中的extern add和sub相同的签名
class test
{
public:
test();
~test();
private:
int add(int a, int b);
int sub(int a, int b);
}
test.cpp调用测试类构造函数中测试类的实现add函数,同时包含这两个文件。
#include "test.h"
#include "file.h" // Contains extern methods
#include <iostream>
test::test()
{
int addition = add(10, 10);
printf("Addition: %d ", addition );
}
int
test::add(int a, int b)
{
return 10;
}
int
test::sub(int a, int b)
{
return 10;
}
main.cpp
#include "test.h"
int main()
{
test *a = new test();
}
现在我的问题是在主课堂上要打印什么。是否会打印
它将输出作为添加:10为什么给10
?Is class test
使用其自己的函数add()
和sub()
。因为这两个函数都存在于file.h
和同一个类中。我的猜测是,它将为函数提供ambiguity
。有标准吗?如果有,请解释。以及如何在class test
中使用文件.h中的函数。
在test
类内部调用add
将使用add
成员函数。
要调用全局add
函数,请使用全局作用域解析运算符::
:
int addition = ::add(10, 10);
use也可以使用名称空间来实现。在文件.h 中
#include "file.h"
namespace file
{
int add(int a, int b)
{
return 20;
}
int sub(int a, int b)
{
return 20;
}
}
测试中.cpp
#include "test.h"
#include "file.h"
#include <iostream>
test::test()
{
int addition = file::add(10, 10); // used namespace here
printf("Addition: %d ", addition );
}
int
test::add(int a, int b)
{
return 10;
}
int
test::sub(int a, int b)
{
return 10;
}
相关文章:
- 内联函数中具有内部链接的全局变量
- 为什么虚函数不能是静态的和全局的?
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局作用域中函数指针的赋值
- 在命名空间中使用全局命名空间中的函数
- C++ 在编译时具有函数计算全局变量
- 在具有全局类型def的类中使用成员函数指针
- 修改程序的入口点时未调用全局变量的构造函数
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- 全局函数参数
- std::线程不是全局变量,但在到达创建它的函数的末尾时不会超出范围?
- 初始化与函数输入相关的全局数组
- 删除全局隐式函数 - 避免使用不明确的运算符
- 如何在全局变量的构造函数之前运行函数
- 如何定义全局函数指针并分配给特定地址
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 在函数中用不同的名称引用全局向量
- 如何在一个结构体中为多个函数全局存储数据