我试图将类对象声明为 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; ^
我看过了 Issue declaring extern class object 和 '[Class name]' does not name a type in 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;
}
b1.h
#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;
}
c1.h
#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_b1
与 class c1
没有任何关系,因此从 c1.h
中删除 extern b1 obj_b1;
。
现在,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.cpp
移动到 b1.cpp
关于C++ extern 类没有命名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52195795/