C++编译具有相同函数名的多个文件

标签 c++ c

在printNumbers.h文件中

//Write a function getNumber() and put your favourite number inside! 
//I will then compile the program and print everyone's favourite number!
int getNumber(void);

如果我想要像不断打印出三个人最喜欢的数字这样的东西

int main() {
    int counter = 0;
    while(counter < 9999) {
         if(counter % 3 == 0) {
             //Print out the first person's number
             printf("My number is %d\n", getNumber();
         } else if (counter % 3 == 1) {
             //Print out the second person's number
             printf("My number is %d\n", getNumber();
         } else {
             //Print out the third person's number
             printf("My number is %d\n", getNumber();
         }

         //Keep printing everyone's numbers until counter reaches 9999

         counter++;
    }
    return 0;
}

3 个人给我他们编写的 C++ 文件,我将每个文件重命名为 A.cpp B.cpp C.cpp。它可能是随机顺序,所以他们不知道他们的文件最终会是 A B 还是 C

他们可能编写的 c++ 文件示例

int getNumber() {
    //Each person can write their own function to return whatever number they want
    int myNumber = 1;
    return myNumber;
}

无论如何,我是否可以编译程序并使用 A.cpp 中的 getNumber() 进行第一次调用,第二次调用使用 B.cpp,第三次调用使用 C.cpp,然后重复.

我可以在 while 循环中命名函数名称 getNumber1() getNumber2() getNumber3() 并更改三个 C++ 文件中的函数名称,但是当有人编写 getNumber() 函数时,他们不知道它是否会结束最多是 A B 或 C。每个人的 getNumber() 函数都应该称为 getNumber()。

.

编辑:很多人都在建议命名空间。我无法控制 .h 文件和人们获得的 ADT,因此他们编写的程序不会使用 namespace 。还有很多人可能会向我提交 C++ 文件,我不得不将它们随机分为 3 组(因为我的程序只能打印 3 个人的号码)所以他们不知道要使用什么命名空间。 .

编辑:一些人建议修改 .h 文件或人们编写的程序。我们都得到了 .h 文件,我们无法更改它。我们将文件(如示例)提交给学校,他们能够执行我的主要功能(我不知道他们是怎么做到的)。我的主要功能将允许用户在提交之前更好地测试他们的 getNumber() 功能,因此它是学校的一个单独程序,用户可以选择使用。

如果有什么令人困惑或不清楚的地方,请向我提问以澄清我的问题!

谢谢。

最佳答案

假设您正在获取他们的 cpp 文件,您不想更改这些文件,而不是编译和链接它们,您可以像这样将它们包含在您的 cpp 中

namespace A {
  #include "A.cpp"
}
namespace B {
  #include "B.cpp"
}
namespace C {
  #include "C.cpp"
}

int main ()
{
  A::getNumber();
  B::getNumber();
  C::getNumber();
}

关于C++编译具有相同函数名的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37628663/

相关文章:

c++ - SSE 复制数据到变量

c - 如何在 C 中获取未格式化的可变长度字符串中的所有 float ?

java - 有什么方法可以释放通过 JNI/JNA 绑定(bind) C 代码而生成的 Java 代码中的内存?

c++ - 为什么需要类型转换 (UINT)(void*)(DWORD)?

c++ - 如何防止在 argv 中丢失双引号?

c++ - 在 C++11 函数中使用尾随返回类型的优势

c++ - R6010-当 boost 文件系统的重命名或 copy_file 方法被命中时,中止被命中

c - 如何在main()之外使用 `malloc`?

c - 1000 位数字的 13 个相邻数字的最大乘积

c++ - 检查一个线程是否完成发送另一个参数给它