簡體   English   中英

外部變量聲明在C ++中不起作用(崩潰與頭文件)

[英]External variable declarations not working in C++ (crashing with header file)

我一直在編寫代碼來模擬一些傳導傳遞問題,但是我一直陷在網格的生成上。 這是因為我可能使用了錯誤的變量聲明...主要:

#include <iostream>
#include <fstream>
#include <string>
#include "library.h"
using namespace std;

int main (void){
    // Number of divisions
    int xdivA, xdivB, ydivA, ydivB, ydivAB;
    xdivA=30; xdivB=30; ydivA=30; ydivB=30; ydivAB=30;
    int N=xdivA+xdivB;
    int M=ydivA+ydivB+ydivAB;
    struct controlvolume celln[N][M];
}

頭文件:

//GLOBAL VARIABLES
extern int N;
extern int M;

//STRUCTURE TYPES
    struct prop {
        double rho, Cp, k;
    };
    struct points {
        double x, y;
    };
    struct controlvolume {
        points coord;
        prop localmaterial;
    };

// FUNCTIONS
double Mesh(controlvolume celln[N][M], int xdivA, int xdivB, int ydivA, int ydivB, int ydivAB,  points initialp[4], prop materials [4]);

Mesh.cpp

#include <iostream>
#include "library.h"
using namespace std;

double Mesh(controlvolume celln[N][M], int xdivA, int xdivB, int ydivA, int ydivB, int ydivAB, points initialp[4], prop materials[4]){
    celln[2][2].coord.x=initialp[3].x;
    celln[2][2].localmaterial.rho=materials[2].rho;

}

所有使用的變量,例如initialp,material等,都在main函數中聲明。 為了節省空間,我沒有在此處包括它們。

我得到的錯誤是:

[錯誤]數組綁定不是']'標記之前的整數常量

[錯誤]數組綁定不是']'標記之前的整數常量

[錯誤]預期在','標記之前的')'

[錯誤]預期在'int'之前的unqualified-id

當定義了網格功能時,它似乎在library.h文件中。

我感謝您的幫助!!! :)

在C ++中,數組的維數必須是編譯時常量。 例如:

 int N=xdivA+xdivB;

不是任何常量,因此您需要將其定義為一個常量:

 const int N=xdivA+xdivB;

同樣,對於程序中的其他變量。

您不能在C ++中創建具有動態大小的數組。 celln[N][M] NM在編譯時必須已知。 更改NM以編譯時間常數或使用類似std::vector東西。

數組的大小在編譯時必須是一個已知的常數。 如果不是這種情況,您會得到一個錯誤

N=xdivA+xdivB; // This declaration should change to

const int N=xdivA+xdivB;

如果希望有一個大小可變的數組,其大小在以后確定,請考慮使用std::vector ,可以在運行時調整大小。

暫無
暫無

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

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