【问题标题】:vector of structs giving error "not declared in this scope"给出错误“未在此范围内声明”的结构向量
【发布时间】:2011-11-04 20:45:49
【问题描述】:

我有一个声明如下的结构:

#ifndef PLAYLIST_H
#define PLAYLIST_H
#include <iostream>
#include <string>
#include <vector>
#include "playlistitem.h"
#include "song.h"
#include "time.h"
struct Playlist {
    std::vector<Song> songs;
    Time cdTotalTime;
    int totalTime;
};

和在另一个文件中声明的 struct Song:

#ifndef SONG_H
#define SONG_H
#include "playlist.h"
#include "time.h"
struct Song {
    std::string title;
    std::string artist;
    std::string album;
    int track;
    Time length;
};

我在标头中有两个结构定义,并且它们都被#included 了。

编译时出现错误

std:vector<Song> songs;

错误“歌曲”未在此范围内声明

我错过了什么?

【问题讨论】:

  • 你确定在文件中包含了Song的定义文件,定义了Playlist?并且它在同一个命名空间中?
  • 你是如何“将他们包括在内”的? (提示:你不是;))
  • 请向我们展示您使用定义的文件。

标签: c++ data-structures vector struct initialization


【解决方案1】:

playlist.h 包括歌曲.h

song.h 不应包含 playlist.h

标头保护防止无限递归,它们不修复循环依赖。

目前 song.h 确实包含 playlist.h。然后当 playlist.h 包含 song.h 时,什么也没有发生(因为 header 保护),并且 Song 没有定义。所以 playlist.h 会产生错误。

【讨论】:

    【解决方案2】:

    不仅你的主文件,而且声明Playlist 的文件也应该#include Song 所在的文件。

    【讨论】:

      【解决方案3】:

      Song 的定义必须先于 Playlist 的定义。由于它们位于不同的标头中,因此您应确保 Playlist 的标头包含 Song 的标头,并且两者都有适当的标头保护。

      【讨论】:

        【解决方案4】:

        您的标题以循环方式相互包含。这是无用和不必要的。为什么你的song.h 包括playlist.h?从song.h 中删除#include "playlist.h" 应该可以修复错误。

        【讨论】:

          【解决方案5】:

          您可以通过将struct Song; 放入标头中为Song 制作原型,并将标头包含在您的.c/.cpp 文件中。这具有更快的编译时间! :D

          只要您正确安排它们,递归包含可以与包含保护一起正常工作。我总是尝试在 .h 文件中包含最少数量的标头,将它们留给源文件。

          另外,我没有在您的代码中看到#endif。现在我假设你的代码实际上有它;)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-04-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-10
            • 2015-06-23
            相关资源
            最近更新 更多