【问题标题】:Functions Calls Across Multiple C++ Source Files跨多个 C++ 源文件的函数调用
【发布时间】:2018-04-01 04:34:20
【问题描述】:

我对在 c++ 中使用头文件非常陌生,并且在使用一个源文件中定义的另一个源文件中的方法时遇到了问题。我已将源文件与头文件链接起来。

定义.cpp:

#include "header.h"
int c::foo (int bar){

return bar;
}

function_call.cpp:

#include "header.h"
int c::other_function( int num ){

int b = foo(num);

return b;
}

header.h:

#ifndef HEADER_H_
#define HEADER_H_

class c {

public:
int foo(int bar);
}

#endif /*HEADER_H_*/

我的 function_call.cpp 出现编译错误:

error: 'foo' was not declared in this scope

我是不是忽略了什么?

【问题讨论】:

  • 我认为您的代码位不是真实的。如果您将代码 sn-ps 传递给编译器,那么第一个错误将是非常干净的error: ISO C++ forbids declaration of ‘foo’ with no type [-fpermissive]。下一个错误是error: ; missing after class declaration。要达到您引用的错误,代码和包含必须不同。

标签: c++ header-files declaration definition


【解决方案1】:

我认为

class c {

public:
foo(int bar);
}

应该是

class c {

public:
int foo(int bar);
}

你不能在没有明确设置返回类型的情况下声明一个函数。

为了让你的例子正常工作,你还需要在header.h中声明other_function并且至少有一个main函数。

【讨论】:

    【解决方案2】:

    我认为你应该在源文件中声明函数原型,在源文件中通过头文件包含一个类,就在包含部分之后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多