【问题标题】:Access member function of another .cpp within same source file?访问同一源文件中另一个 .cpp 的成员函数?
【发布时间】:2009-08-20 04:58:50
【问题描述】:

我正在使用 Visual C++。我在同一个源文件中有两个 .cpp 文件。如何在这个主 .cpp 中访问另一个类 (.cpp) 函数?

【问题讨论】:

  • 你能解释一下为什么你不想使用头文件吗?这可能有助于帮助您解决问题。
  • 我不认为他说过他不想这样做。看起来他不知道如何

标签: c++ class


【解决方案1】:

您应该在 .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.cppuse_me.cpp 中的 #include 指令的位置。这基本上就是#include 所做的。你这样做是愚蠢的,但它肯定是可以做到的。
  • use_me.h 不必与main.cpp 在同一目录中,因为您可以像#include &lt;some_path/use_me.h&gt; 一样包含它
【解决方案2】:

不创建头文件。使用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
【解决方案3】:

您应该将函数声明放在 .hpp 文件中,然后将 #include 放在 main.cpp 文件中。

例如,如果你调用的函数是:

int foo(int bar)
{
   return bar/2;
}

你需要用这个创建一个 foobar.hpp 文件:

int foo(int bar);

并将以下内容添加到所有调用 foo 的 .cpp 文件中:

#include "foobar.hpp"

【讨论】:

  • 简单地说,another.cpp class A { ----- } 和 main.cpp 中,有没有可能在 main.cpp 中创建类 A 的对象?
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 2020-03-21
相关资源
最近更新 更多