在c ++中的类之间使用结构 [英] Using a struct across classes in c++
问题描述
我还是相当新的c ++所以请允许!
基本上我已经在头文件中为我的一个类充满了字符串创建了一个结构。
I am still fairly new to c++ so please allow! Essentially I have created a struct in the header file for one of my classes full of strings.
typedef struct details{
string name;
string address;
}details;
我希望不仅在属于标题的cpp文件中使用此结构,其他类。例如,我想在另一个头文件中创建此结构的向量。
and I wish to not only use this struct in the cpp file that belongs to the header, but in other classes as well. For example, I want to create a vector of this struct in another header file.
private:
vector <details> foo;
我也想在主
details d;
d.name = "hi";
d.address = "hello";
但是,当我目前尝试这样做时,会出现错误,例如
however when I currently try to do this I get errors such as
error: 'details' was not declared in this scope
vector <details> foo;
和
error: template argument 1 is invalid
vector <details> foo;
有任何人有类似的问题,可以提供我可以做什么来解决这个问题?非常感谢。
has anyone had similar issues who can provide insite into what I can do to fix this? Thanks a lot.
编辑演示码
class1.h
class1.h
#include "class2.h"
struct trans1{
string name;
};
class class1 {
private:
vector <trans2> t2;
public:
class1();
};
class2.h
#include "class1.h"
struct trans2{
string type;
};
class class2{
private:
vector <trans1> t1;
public:
class2();
};
错误纪录:
In file included from class1.h:3:0,
from class1.cpp:1:
class2.h:21:13: error: 'trans1' was not declared in this scope
vector <trans1> t1;
^
class2.h:21:19: error: template argument 1 is invalid
vector <trans1> t1;
^
class2.h:21:19: error: template argument 2 is invalid
我知道这是在现实世界应用程序中可笑的代码,但这是我可以演示的最简单的方法
I understand that this is ridiculous code in a real world application however this is the simplest way I could demonstrate
推荐答案
必须包含包含 struct
定义的头文件。
You have to include the header file that contains the definition of the struct
everywhere you use it.
只有当你只声明引用或指针时,你不需要的唯一情况是:在这种情况下你可以向前声明它:
The only cases where you don't have to is when you are only declaring references or pointers to it; in that case you can just forward declare it with:
struct details;
也可以在C ++中声明:
Also in C++ you can just declare it with:
struct details{
std::string name;
std::string address;
};
真的不需要 typedef
。
这篇关于在c ++中的类之间使用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!