试图制作电子鸡程序,但编译器抛出未定义的对“Tamagotchi::age()”错误的引用
理想情况下,这段代码会返回电子鸡的年龄,它应该在开始时由类的构造函数初始化为 0。
我显然在某个地方搞砸了,但不确定在哪里,如果有人看到哪里并能帮助我理解那会很棒!
此外,如果您发现编码实践不佳,我是新手,正在寻求改进,因此欢迎任何帮助。
编辑:糟糕,我忘了从类中复制和粘贴函数定义。它们在那里,但我仍然遇到编译器错误。
//tamagotchi.cpp
#include "tamagotchi.h"
#include
/* return of Tamagotchi information */
std::string Tamagotchi::name() {return myName;}
int Tamagotchi::age() {return myAge;}
int Tamagotchi::happiness() {return myHappiness;}
int Tamagotchi::hunger() {return myHunger;}
bool Tamagotchi::rIsSick() {return isSick;}
-
//tamagotchi.h
#ifndef TAMAGOTCHI_H
#define TAMAGOTCHI_H
#include
class Tamagotchi
{
công cộng:
/* initialization of default for tamagotchi */
Tamagotchi()
: myName ("Default"),
myAge ( 0 ),
myHappiness ( 0 ),
myHunger ( 0 ),
isSick ( false ) { }
/* returning tamagotchi variables */
std::string name();
int age();
int happiness();
int hunger();
bool rIsSick();
riêng tư:
std::string myName;
int myAge;// defined from 0 - 50 based on hours
int myHappiness;// defined from 0 - 10
int myHunger; // defined from 0 - 10, greater is hungrier
bool isSick;// defines whether or not the Tamagotchi is sick
};
#endif
-
//main.cpp
#include "tamagotchi.h" // defines tamagotchi class
#include
#include
int chính(){
Tamagotchi myTamagotchi;
std::cout << myTamagotchi.age();
trả về 0;
}
Cảm ơn
您必须在类声明中的头文件中声明您的访问器函数(或与此相关的任何成员函数):
class Tamagotchi
{
công cộng:
/* initialization of default for tamagotchi */
Tamagotchi()
: myName ("Default"),
myAge ( 0 ),
myHappiness ( 0 ),
myHunger ( 0 ),
isSick ( false ) { }
riêng tư:
std::string myName;
int myAge;// defined from 0 - 50 based on hours
int myHappiness;// defined from 0 - 10
int myHunger; // defined from 0 - 10, greater is hungrier
bool isSick;// defines whether or not the Tamagotchi is sick
công cộng:
std::string name();
int age();
int happiness();
int hunger();
bool rIsSick();
};
一些提示:将不修改对象状态的成员函数声明为 const 很有用,如下所示:
std::string name() const;
您还必须相应地修改 cpp 文件中的定义:
std::string Tamagotchi::name() const {...}
我还建议您通过 const 引用返回容器对象,例如 std::string:
const std::string& name() const;
同样,你必须修改cpp文件中的定义:
const std::string& Tamagotchi::name() const { return myName; }
如果按值返回它,正如您所做的那样,您将始终创建返回字符串的拷贝,这可能会导致性能下降。通过 const 引用返回可以避免这种情况。然而,这仅对容器和其他大型对象有用。基本类型(int、float、bool 等)和小类的实例等简单事物几乎可以无成本地按值返回。
Tôi là một lập trình viên xuất sắc, rất giỏi!