簡體   English   中英

C ++ extern類未命名類型

[英]c++ extern class does not name a type

我試圖將一個類對象聲明為extern但出現以下錯誤:

 g++ a1.cpp -std=c++11 In file included from b1.h:5:0, from a1.cpp:2: c1.h:6:8: error: 'b1' does not name a type extern b1 obj_b1; ^ 

我查看了在聲明外部類對象的問題中“ [Class name]”未在C ++中命名類型

我認為我正在按照此處提到的步驟進行操作。 但是找不到問題所在。

文件是:

a1.cpp

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

b1 obj_b1;


int main(){

    //access object from class B
    std::cout << " test  " << std::endl;
    std::cout << " obj_b1 value is   " << obj_b1.value << std::endl;
    obj_b1.value = 6;
    return 0;
}

1小時

#ifndef CLASS_B1
#define CLASS_B1

#include "c1.h"

class b1{
public:
    int value=5;
    int print_value();
};
#endif

b1.cpp

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

int b1::print_value(){
        std::cout << "value in b1 is " << value << std::endl;
}

1小時

#ifndef CLASS_C1
#define CLASS_C1
#include "b1.h" // this is an attempt to fix issue, but didnt work

extern b1 obj_b1; // Is there a better place to declare this ?

class c1 {
private: 
    int c1_value=10;
    int c1_print_value();
};
#endif

c1.cpp

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

int c1::c1_print_value()
{
    std::cout << "in c1 , value is " << c1_value << std::endl;
    std::cout << " obj_b1.value is " << obj_b1.value << std::endl;
    return 0;
}

當我在extern聲明的上方添加b1.h時,我不明白為什么編譯器會抱怨b1 有人可以幫助解決問題嗎?

b1.h包括c1.h ,而c1.h包括b1.h 這是一團糟。 通過使用#indef / #define組合,您可以防止無限遞歸,但是仍然很麻煩。

obj_b1class c1沒有任何關系,因此刪除extern b1 obj_b1; 來自c1.h

現在c1.h不再依賴於c1.h中的任何b1.h ,因此您可以從c1.h刪除#include "b1.h" 出於類似的原因,您應該從b1.h刪除#include "c2.h"

另一方面,c2.cpp 確實取決於obj_b1 (假設obj1.name是一個錯字,應該是obj_b1.name ),因此您應該將extern b1 obj_b1; b1.h#include "b1.h"c2.cpp

為了進行一些額外的清理,請移動b1 obj_b1; a1.cppb1.cpp

暫無
暫無

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

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