gpt4 book ai didi

c++ - 头文件和命名空间混淆

转载 作者:行者123 更新时间:2023-11-28 07:27:38 24 4
gpt4 key购买 nike

我正在尝试将 Album 对象从 main 发送到另一个 .cpp 文件中的函数,但在编译时出现错误:

我从 main 创建一个 Album 对象,然后尝试将它传递给菜单函数,如下所示:

Model::Album album("TestAlbum");
View::Menu m;
m.startMenu(album);

我的菜单类:

#include "stdio.h"
#include "Menu.hpp"
#include "AlbumOps.hpp"
#include "Album.hpp"
#include <iostream>
using namespace std;

namespace View
{
void Menu::startMenu(Model::Album inAlbum) //compile errors happen here
{
int option = 1;
while (option!=5)
{
cout << "1. Add image to album\n";
cout << "2. Remove image from album\n";
cout << "3. List all images in album\n";
cout << "4. View image in album\n";
cout << "5. Quit\n";
//and so on

当我尝试编译它时,在 void Menu::startMenu(Model::Album inAlbum) 行出现错误

“模型”尚未声明

模型是我使用的命名空间。我以为包括 Album.hpp 会解决这个问题,但它没有,我不知道如何解决这个问题。

编辑:菜单是一个类,这是我的Menu.hpp:

#ifndef MENU_H //"Header guard"
#define MENU_H

namespace View
{
class Menu
{
public:
void startMenu(Model::Album inAlbum);
};
}
#endif

还有我的Album.hpp:

#ifndef ALBUM_H
#define ALBUM_H

#include <string>
#include <vector>
#include "Image.hpp"

namespace Model{
class Album
{
private:
std::vector<Image*> imageList;
std::string albumName;


public:
Album(std::string);

/****Setters****/
void setAlbumName(std::string);
void addImage(Image);

/****Getters****/
Image getImage(int);
std::string getAlbumName();
int getListLength();
};
}
#endif

最佳答案

您的 Menu.hpp 缺少一些声明。 header 应该可以自行编译,而不需要在它们之前包含其他 header 。所以如果你不确定你应该总是尝试编译这样的东西:

#include "Menu.hpp"

int main() {
}

如果编译不通过,需要在header中添加include或者declaration

现在您的 Menu.hpp 中缺少的是 Album 类的声明。只包含相册标题会过分杀伤力并导致循环包含,因此前向声明是正确的做法:

#ifndef MENU_H //"Header guard"
#define MENU_H

//forward declaration of Album:
namespace Model {
class Album;
}

namespace View
{
class Menu
{
public:
void startMenu(Model::Album inAlbum);
};
}
#endif

在您的相册标题中,图像标题包含的内容过多。前向声明就足够了,因为您实际上并不使用 Image,您只使用指向 Image 的指针并将其类型声明为某些函数的返回值和参数类型。不过,您可能需要在 Album.cpp 中包含图片标题。

有关包含和转发声明的更多信息,请阅读 this excellent GOTW article from Herb Sutter .

关于c++ - 头文件和命名空间混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18435671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com