我想使用Struct,但不知道在哪里定义它。这是我目前的代码:
Header file (Datos.h)
#ifndef DATOS_H
#define DATOS_H
using namespace std;
class Datos {
public:
Datos();
void rellenarDatos();
struct KeyData;
struct BBDD;
};
Implementation File (Datos.cpp)
#include <string>
#include <string.h>
#include "Datos.h"
using namespace std;
Datos::Datos() {
};
struct KeyData {
int Key;
string data;
};
struct BBDD {
KeyData DNI[N];
KeyData Nombre[N];
KeyData Apellido[N];
KeyData Direccion[N];
};
void Datos::rellenarDatos() {
BBDD.DNI[i].Key = 100;
BBDD.Nombre[i].Key = 100;
BBDD.Apellido[i].Key = 100;
BBDD.Direccion[i].Key = 100;
BBDD.DNI[i].data = "hello";
BBDD.Nombre[i].data = "hello";
BBDD.Apellido[i].data = "hello";
BBDD.Direccion[i].data = "hello";
};
编译器将如下所示丢弃错误:
Datos.cpp:25:7: error: expected unqualified-id before ‘.’ token
BBDD.DNI[i].Key = 100;
问题出在哪儿?谢谢。
最佳答案
有几个问题。
首先,BBDD
是一种类型,而不是对象。
这是错误消息的直接原因。
其次,在类定义中,您在Datos
类的范围内前向声明了两个结构。
这些的全名是Datos::KeyData
和Datos::BBDD
,因此要定义它们,您可以编写
struct Datos::KeyData {
int Key;
string data;
};
struct Datos::BBDD {
Datos::KeyData DNI[N];
Datos::KeyData Nombre[N];
Datos::KeyData Apellido[N];
Datos::KeyData Direccion[N];
};
另一方面,您似乎想要具有
BBDD
类型的成员。在这种情况下,请将定义放入类定义中:
class Datos {
public:
Datos();
void rellenarDatos();
struct KeyData {
int Key;
string data;
};
struct BBDD {
KeyData DNI[N];
KeyData Nombre[N];
KeyData Apellido[N];
KeyData Direccion[N];
};
BBDD bbdd;
};
// ...
void Datos::rellenarDatos() {
// ...
bbdd.DNI[i].Key = 100;
// ...
};
关于c++ - 结构问题(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756303/