c++ - 结构问题(C++)

标签 c++ struct compiler-errors

我想使用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::KeyDataDatos::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/

相关文章:

c++ - FindNextFile 因空格字符而失败

c++ - 具有不同类型元素和使用类的二维数组

c++ - 如何将二维数组的行(和列)相加

c++ - C/C++结构问题

c - C 中的静态结构不改变值

c++ - 在 C++ 中,获取/释放原子访问与宽松访问与栅栏相结合之间是否存在任何有效区别?

c - Turbo C 错误 "declaration is not allowed here"(结构和文件操作)

c++ - StarCluster错误中的C++程序编译

Java 编译器错误 : Missing Return Statement

c++ - objectdetect.hpp 的 Opencv 2.4 编译错误