我正在尝试使用play()函数设置一个新类.我不确定我做错了什么,因为我有其他课程,我以类似的方式实施,他们工作正常.有人可以指出我可能犯了错误吗?
.h文件
#ifndef GAME_H
#define GAME_H
#include <string>
using namespace std;
class Game {
public:
Game();
void play();
};
#endif
Run Code Online (Sandbox Code Playgroud)
.cpp文件
#include "game.h"
#include <string>
#include <iostream>
using namespace std;
Game::Game() {}
Game::play() {}
Run Code Online (Sandbox Code Playgroud)
我将play功能调用如下:
Game* theGame = new Game();
theGame->play();
Run Code Online (Sandbox Code Playgroud)
我编译时遇到以下错误:
game.cpp:10: error: ISO C++ forbids declaration of ‘play’ with no type
game.cpp:10: error: prototype for ‘int Game::play()’ does not match any in class ‘Game’
game.h:16: error: candidate is: void Game::play()
game.cpp:10: error: ‘int Game::play()’ cannot be overloaded
game.h:16: error: with ‘void Game::play()’
Run Code Online (Sandbox Code Playgroud)
第一个错误:
Game::play() {}
Run Code Online (Sandbox Code Playgroud)
应该
void Game::play() {}
Run Code Online (Sandbox Code Playgroud)
第二个 - 你using namespace std;的标题中有.永远不要那样做.不是说错误,而是坏习惯.
第三 - 你已经#include <string>在标题中,虽然你没有使用string,所以它没用,并且会影响编译时间.
第四 - 你用new:).请谷歌智能指针.这是C++,原始指针的使用应该是最小的.