在头文件中通过引用传递参数

时间:2016-04-28 18:59:23

标签: c++

我有3个文件:

file1.h

#ifndef FILE_H_INCLUDED
#define FILE_H_INCLUDED

#include <stdbool.h>  // To prevent unknown type 'bool' error
bool parse(char** &buffer);

#endif

file1.cpp

#include "file1.h"
#include <iostream>

using namespace std;

bool parse(char** &buffer) {
  buffer[0] == "test";
}

file2.cpp包含file1.h并使用char **缓冲区调用parse();

编译时我得到:

error: expected ';', ',' or ')' before & token

我错过了什么?

编辑:我正在构建一个使用原始套接字的项目,它主要是C代码。

4 个答案:

答案 0 :(得分:2)

您使用的是C编译器,而不是C ++编译器。

答案 1 :(得分:0)

我认为你真正要做的是传递一个char指针数组,因此你可以将函数改为

bool parse(char** buffer);

答案 2 :(得分:0)

在C语言模式下,编译器抱怨&符号:

bool parse(char ** &buffer)

C语言不允许该上下文中的&字符。

但是,它是有效的C ++语法,因为该函数需要通过引用传递指针。

正如其他人所说,切换到C ++编译器或告诉编译器将文件编译为C ++语言。

答案 3 :(得分:0)

这个线索:

bool parse(char** &buffer) {
  buffer[0] == "test";
}

表示'buffer'是对某种字符串数组的某种引用。不知道为什么它会返回一个bool(无论如何你都忽略了。)

你应该考虑:

// a std::vector of std::string
typedef  std::vector<std::string>  StrVec_t;

// parse can easily add individual std::strings 
// to the std::vector (from some unknown source)
bool parse (StrVec_t& buffer) 
{
    buffer.push_back(std::string("test"));  // tbd - where did 'test' come from?
    return(true);  // and add some meaning to this, or perhaps remove
}

// and is used as
// ...
StrVec_t  myWords;
// ...
// ...
(void)parse(myWords); // update myWords from some other source
// ...                // example of how to discard bool