【发布时间】:2009-08-20 04:58:50
【问题描述】:
我正在使用 Visual C++。我在同一个源文件中有两个 .cpp 文件。如何在这个主 .cpp 中访问另一个类 (.cpp) 函数?
【问题讨论】:
-
你能解释一下为什么你不想使用头文件吗?这可能有助于帮助您解决问题。
-
我不认为他说过他不想这样做。看起来他不知道如何。
我正在使用 Visual C++。我在同一个源文件中有两个 .cpp 文件。如何在这个主 .cpp 中访问另一个类 (.cpp) 函数?
【问题讨论】:
您应该在 .h 文件中定义您的类,并在 .cpp 文件中实现它。然后,将您的 .h 文件包含在您想要使用类的任何位置。
例如
文件 use_me.h
#include <iostream>
class Use_me{
public: void echo(char c);
};
文件 use_me.cpp
#include "use_me.h" //use_me.h must be placed in the same directory as use_me.cpp
void Use_me::echo(char c){std::cout<<c<<std::endl;}
main.cpp
#include "use_me.h"//use_me.h must be in the same directory as main.cpp
int main(){
char c = 1;
Use_me use;
use.echo(c);
return 0;
}
【讨论】:
Use_me 类声明并将其粘贴到 main.cpp 和 use_me.cpp 中的 #include 指令的位置。这基本上就是#include 所做的。你这样做是愚蠢的,但它肯定是可以做到的。
use_me.h 不必与main.cpp 在同一目录中,因为您可以像#include <some_path/use_me.h> 一样包含它
不创建头文件。使用extern 修饰符。
a.cpp
extern int sum (int a, int b);
int main()
{
int z = sum (2, 3);
return 0;
}
b.cpp
int sum(int a, int b)
{
return a + b;
}
【讨论】:
extern。
您应该将函数声明放在 .hpp 文件中,然后将 #include 放在 main.cpp 文件中。
例如,如果你调用的函数是:
int foo(int bar)
{
return bar/2;
}
你需要用这个创建一个 foobar.hpp 文件:
int foo(int bar);
并将以下内容添加到所有调用 foo 的 .cpp 文件中:
#include "foobar.hpp"
【讨论】: