簡體   English   中英

編寫C ++函數以對外部聲明的數組進行操作

[英]Writing a C++ function to operate on arrays declared externally

我正在嘗試編寫一組實現數組上各種操作的C ++函數( aha.cpp )。 實際的數組將在其他文件( bhb.cppchc.cpp等)中定義。

我的目標是任何項目都可以#include "ah"並在該項目中定義的數組上運行這些功能。 我不想在ah本身中包含任何內容,因為我希望將來的任何項目都可以使用ah而無需重寫它。 但是,我不知道如何使用extern來做到這一點。

這是到目前為止我所擁有的玩具示例。 a實現了一個函數f ,該函數將用於尚未指定的數組。

// this is not right, but I'm not sure what to do instead
extern const int ARRAY_LEN;
extern int array[ARRAY_LEN]; // error occurs here

void f();

a.cpp

#include "a.h"

// Do something with every element of "array"
void f() {
  for(int i=0; i < ARRAY_LEN; i++) {
    array[i];
  }
}

現在,項目b定義了數組,並希望在其上使用函數f

BH

const int ARRAY_LEN = 3;

cpp文件

#include "a.h"
#include "b.h"

int array[ARRAY_LEN] = {3, 4, 5};

// Some functions here will use f() from a.cpp

編譯時,我得到:

In file included from b.cpp:1:0:
a.h:2:27: error: array bound is not an integer constant before ‘]’ token

我閱讀了以下其他相關問題:

...但是我看不到如何將解決方案應用於我的案子。 問題是通常人們最終會#include include-添加用於定義數組的文件,而我想以另一種方式來做:在新項目中定義數組,然后#include在該項目上操作的共享函數集數組。


編輯1:如果我更換的聲明arrayah用下面,通過@的建議id256:

extern int array[];

然后我得到另一個錯誤:

multiple definition of `ARRAY_LEN'

編輯2:我也嘗試從以下答案:

為什么“ extern const int n;” 不能按預期工作?

基本上,我在bh中添加了“ extern const int ARRAY_LEN”,以“強制外部鏈接”。 所以現在:

BH

extern const int ARRAY_LEN;
const int ARRAY_LEN = 3;

..和所有其他文件與原始文件相同。 但是我得到了相同的原始錯誤:

a.h:2:27: error: array bound is not an integer constant before ‘]’ token

將數組聲明為extern ,無需指定大小(對於多維數組,除第一維外,您還需要所有其他大小)。 只需使用:

extern int array[];

或者,在ah中添加bh(在聲明數組之前),以便在聲明數組時可見ARRAY_LEN的定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM