【问题标题】:Error: undefined reference to 'player()'错误:未定义对“播放器()”的引用
【发布时间】:2023-03-24 01:48:02
【问题描述】:

各位程序员!我正在寻求进入游戏开发,所以我正在尝试编写自己的非常简单的文本战斗模拟器。您可以选择玩家名称并与您选择的怪物战斗。无论如何,我的目标是首先编写简单的代码,然后扩展并添加更多类。这是我目前仅有的两个文件:

player.h

#ifndef PLAYER_H
#define PLAYER_H

#include <string>
using std::string;


class player
{
public:
player();

const int maxHealth = 100;
int armorModifier = 0;
int playerLevel = 1;
int gold = 0;
int currentHealth = maxHealth;

string Name;

~player();
};
#endif // PLAYER_H

BattlesMain.cpp

/* GAME FEATURES THAT ARE COMMENTED WILL BE IMPLEMENTED AT A LATER TIME */


#include <iostream>
#include "player.h"

using std::cout;
using std::cin;

int main()
{
  /* MAIN MENU */

cout << "Monster Battles: Text Action, v0.1\n";
cout << "Welcome, fighter!\n";
cout << "1.New Game\n";
// cout << "2.Load Game\n";
cout << "3.Quit Game\n";

char choice;

cin >> choice;

/* GAME LOOP */

while (choice !='4')
{
   if (choice == '1')
   {
       player Player1;

       cout << "Arena Host: Hello, fighter. What is your name?\n";
       cin >> Player1.Name;
       cout << "Welcome to the arena, " << Player1.Name << ". Here, you will \n";
       cout << "be given the chance to battle fearsome monsters for fortune and \n";
       cout << "fame. With the gold you win, you can visit our shop to buy new weapons, \n";
       cout << "armor and other useful items. Since you are unarmed, here's a THIEF'S DAGGER. \n";
       cout << "It's not much, but you'll hopefully be able to buy better items later! Good luck!\n";


}

return 0;}

请注意,这是我第一次尝试创建一个小项目,所以请耐心等待任何糟糕的编码风格(非常欢迎提供反馈)。正如我在 cmets 中所说的那样,这是我想做的精简版。问题是,当我尝试执行该文件时,无论我在何处使用 Player1.Name,都会收到错误消息“错误:未定义对 'player()' 的引用。我目前正在使用适用于 Windows 7 的 Code::Blocks。

谢谢!

【问题讨论】:

    标签: c++ reference header syntax-error undefined


    【解决方案1】:

    您没有为构造函数和析构函数提供定义player 类的定义中只有一个声明)。

    如果构造函数和析构函数不应该做任何事情,请不要显式声明它们。编译器会为你隐式生成它们。

    特别是,用户提供的析构函数具有(很可能是不希望的)结果,即禁止隐式生成移动构造函数和移动赋值运算符(而隐式生成复制构造函数和复制赋值运算符仅在 C++11 中被弃用)。

    此外,初始化变量的方式仅在 C++11 之后才允许使用。如果您好奇如何在 C++03 中初始化成员变量,可以使用 constructor's initialization list

    player::player()
        :
        maxHealth(100),
        armorModifier(0),
        playerLevel(),
        gold(0),
        currentHealth(maxHealth)
    {
    }
    

    当然,您必须在类定义中省略初始化器,并且您仍然必须包含构造函数的声明。

    【讨论】:

    • 并且类声明中的成员变量赋值也是不允许的
    • 谢谢你,安迪!那完成了工作;我的程序按预期运行。沃乔:这是为什么?如果我想初始化值(比如我的玩家的恒定最大生命值)怎么办?还有其他方法吗?
    • @DimitrisAlmeidaKokkaliaroglo:是的,还有其他方法可以做到这一点(例如在构造函数的初始化列表中)。但是,在 C++11 中,您正在做的事情是允许的
    • 知道这一点很有用。显示,在旧标准中,我将如何在构造函数中初始化我的变量?出于兼容性原因,我想知道。
    • @DimitrisAlmeidaKokkaliaroglo:我编辑了答案以表明这一点。如果这篇文章回答了您的问题,请考虑将答案标记为已接受:)
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2016-10-03
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多