如何访问类中的全局函数,该类具有与全局函数相同的函数签名

How access global function in class which is having same function signature as global function?

本文关键字:函数 全局 何访问 访问      更新时间:2023-10-16

以下是我的场景:

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;
}