关于 c :Compiling Helper file with functions | 珊瑚贝

Compiling Helper file with functions


我不知所措 – 我刚刚进入 C 语言,但由于某种原因,这对我来说不起作用。所以我正在使用 Netbeans,并且我有以下主文件:

1
2
3
4
5
6
7
8
9
10
11
12
#include <cstdlib>

#include”functions.h”

using namespace std;

int main(int argc, char** argv) {

    f(“help”);

    return 0;
}

Functions.h 文件:

1
2
3
4
5
6
7
8
#include <string>

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

void f( string a );

#endif

和 Functions.cpp 文件:

1
2
3
4
5
#include”functions.h”

void f( string a ) {
    return;
}

所以,长话短说,它不能编译。它说它无法理解字符串变量?我不明白,我尝试将字符串的包含移动到整个地方,但似乎无济于事。我该怎么办?

  • 学会不使用 “using namespace std;”
  • 你可以这样想问题:它的真名不是string——它是std::string。不要使用 using namespace std; 作弊。
  • 为什么?它被认为是不好的做法吗?
  • @user1288167:是的,这是一种不好的做法。简而言之,它首先取消了使用命名空间的所有好处。学习使用命名空间,而不是绕过它们。


你需要在Functions.h中包含字符串头文件,同时告诉编译器string来自std命名空间。

1
2
3
4
5
6
7
#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <string>
void f( std::string a );

#endif

Functions.cpp 文件:

1
2
3
4
5
#include”functions.h”

void f( std::string a ) {
    return;
}

更好的做法是通过 const 引用传递字符串

1
2
3
void f(const std::string& a ) {
    return;
}

请参阅为什么 \\’using namespace std;\\’ 在 C 中被认为是一种不好的做法?

  • 我可以通过在我的其他文件中写入 “using namespace std;” 行来解决这个问题吗?还是把它写进去是个好习惯?
  • 是的,你可以,但这不是好的程序实践。请参阅我关于 using namespace std; 的更新答案
  • @user1288167:请不要养成 using namespace std 的坏习惯。它只会让你和你的同事感到悲伤。
  • 好吧,我不反对学习不使用它,但它为什么会引起悲伤?
  • @user1288167:因为名称不明确。请参阅 bilz 的答案中提供的链接以获得很好的解释。


如果您尝试使用 std::string,则必须在函数头中添加 #include <string>,并将其命名为 std::string,因为它位于 std 命名空间中。

1
2
3
4
5
6
7
8
#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <string>

void f( std::string a );

#endif

请参阅此相关帖子以及为什么在 C 中”使用命名空间标准”被认为是不好的做法?


包括标准标题:<string>

1
#include <string>

来源:https://www.codenong.com/14719035/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8718.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?