如何在具有相同功能签名的类中访问全局函数作为全局函数?

时间:2015-02-10 12:21:18

标签: c++ visual-c++

以下是我的情景:

file.h 此文件包含两个带extern的函数

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 这是一个类测试,其中两个成员函数具有相同的签名,如extern add和sub in file.h

class test
{
    public:
          test();
          ~test();
    private:
         int add(int a, int b);
         int sub(int a, int b);
}

test.cpp 调用测试类构造函数中的测试类的实现添加函数以及包含这两个文件。

#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 为什么要给10class test是否使用自己的函数add()sub()。因为这两个函数都存在于file.h和同一类中。我的猜测是它会给ambiguity函数。有没有标准,如果是这样请解释。 如何使用class test中的file.h 中的函数。

2 个答案:

答案 0 :(得分:1)

add课程中调用test将使用add成员函数。

要调用全局add函数,请使用global scope resolution operator ::

int addition = ::add(10, 10);

答案 1 :(得分:1)

使用也可以使用命名空间。 在file.h中

#include "file.h"
namespace file
{
     int add(int a, int b)
     {
         return 20;
     }

     int sub(int a, int b)
     {
         return 20;
     }
}

在test.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;
}