简体   繁体   English

C ++对象作为参数

[英]C++ Object as argument

I am trying to make a program where I need to pass objects as argument to a function in a class, but it gives me these errors: 我试图制作一个程序,需要将对象作为参数传递给类中的函数,但这给了我这些错误:

------ Build started: Project: C++ Program, Configuration: Debug Win32 ------ ------开始构建:项目:C ++程序,配置:Win32调试------

Main.cpp Main.cpp的
[...]\\game.h(8): error C2061: syntax error : identifier 'Chapter' [...] \\ game.h(8):错误C2061:语法错误:标识符“章节”
[...]\\main.cpp(9): error C2660: 'Game::addChapter' : function does not take 1 arguments [...] \\ main.cpp(9):错误C2660:'Game :: addChapter':函数未采用1个参数

Game.cpp Game.cpp
[...]\\game.h(8): error C2061: syntax error : identifier 'Chapter' [...] \\ game.h(8):错误C2061:语法错误:标识符“章节”
[...]\\game.cpp(20): error C2511: 'void Game::addChapter(Chapter *)' : [...] \\ game.cpp(20):错误C2511:“无效Game :: addChapter(Chapter *)”:
overloaded member function not found in 'Game' 在“游戏”中找不到重载的成员函数
[...]\\game.h(3) : see declaration of 'Game' [...] \\ game.h(3):请参阅“游戏”的声明

My Code: 我的代码:

Main.cpp Main.cpp的

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

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

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

Game.cpp Game.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";
}

Game.h Game.h

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

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

Chapter.cpp Chapter.cpp

#include "Chapter.h"

Chapter::Chapter()
{

}


Chapter::~Chapter()
{

}


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

Chapter.h Chapter.h

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

protected:
    void getInput();
};

Why am I getting this error and how can I solve the problem? 为什么会出现此错误,如何解决该问题?

Include Chapter.h in Game.h . 包括Chapter.hGame.h

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

You need to tell where the compiler can find the definition of Chapter when it reads the definition of addChapter in Game.h . 您需要在读取Game.h中的Game.h时告诉编译器在哪里可以找到Chapter的定义。

You are missing a include to Chapter.h inside of Game.h 您缺少Game.h中Chapter.h的包含内容

#include "Chapter.h"

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

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

With that everything works like you'd expect 这样,一切都会如您所愿

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM