【问题标题】:C++ Object as argumentC++ 对象作为参数
【发布时间】:2015-01-22 04:20:46
【问题描述】:

我正在尝试编写一个程序,我需要将对象作为参数传递给类中的函数,但它给了我这些错误:

------构建开始:项目:C++程序,配置:调试Win32 ------

Main.cpp
[...]\game.h(8):错误 C2061:语法错误:标识符“章节”
[...]\main.cpp(9): error C2660: 'Game::addChapter' : function does not take 1 arguments

游戏.cpp
[...]\game.h(8):错误 C2061:语法错误:标识符“章节”
[...]\game.cpp(20): 错误 C2511: 'void Game::addChapter(Chapter *)' :
在“游戏”中找不到重载的成员函数
[...]\game.h(3) : 参见“游戏”的声明

我的代码:

Main.cpp

#include "Game.h"
#include "Chapter.h"

int main(void)
{
Game game;
Chapter hi;

game.addChapter(&hi);
game.start();
return 0;
}

游戏.cpp

#include "Game.h"
#include <iostream>
#include <vector>
#include <string>
#include "Chapter.h"

using namespace std;

Game::Game()
{

}

Game::~Game()
{

}

void Game::addChapter(Chapter *chapter)
{
    cout << "Added";
}

void Game::start()
{
cout << "Started";
}

游戏.h

#pragma once
class Game
{
public:
    Game();
    ~Game();

    void addChapter(Chapter *chapter);
    void start();
};

章节.cpp

#include "Chapter.h"

Chapter::Chapter()
{

}


Chapter::~Chapter()
{

}


void Chapter::getInput()
{
cout << "Hello";
}

章节.h

#pragma once
class Chapter
{
public:
    Chapter();
    ~Chapter();

protected:
    void getInput();
};

为什么会出现这个错误,我该如何解决这个问题?

【问题讨论】:

  • 我看不到您在哪里告诉我们确切错误是什么以及它与哪些行有关...
  • Chapter 是如何声明的?
  • 您忘记在 Game.h 中包含 Chapter.h。在编译 Game.h 时,编译器不知道 Chapter 是什么,并给你一个错误。
  • @Cameron 这应该是一个答案。
  • @Erik:您没有使用string 中声明的任何内容,但您的问题仍然有效——原因是预处理器将#includes 扩展为包含文件的全文在文件实际编译之前。这意味着给定的 .h 文件具有之前包含的所有文件的上下文(即使它本身不包含这些文件)。在这种情况下,Chapter.h 会看到 Game.h、iostreamvectorstring,因为 main.cpp 在包含 Chapter.h 之前包含了它们。但不要依赖这个,因为另一个 .cpp 可能首先包含不同的东西(或什么都没有!)。

标签: c++


【解决方案1】:

Game.h 中包含Chapter.h

\game.h(8): error C2061: syntax error : identifier 'Chapter

当编译器读取Game.h中addChapter的定义时,你需要告诉编译器在哪里可以找到Chapter的定义。

【讨论】:

  • 你也可以在这种情况下转发声明章节,因为对象大小不需要仅仅指向它。
【解决方案2】:

您在 Game.h 中缺少对 Chapter.h 的包含

#include "Chapter.h"

#pragma once
class Game
{
public:
    Game();
    ~Game();

    void addChapter(Chapter *chapter);
    void start();
};

一切都如你所愿

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2017-08-02
    相关资源
    最近更新 更多