尝试制作Tamagotchi程序,但编译器将未定义的引用抛出给'Tamagotchi :: age()错误
理想情况下,此代码将返回Tamagotchi的年龄,该年龄应在类的构造函数开始时初始化为0。
我显然在某个地方搞砸了,但是不知道在哪里,如果有人看到哪里并且可以帮助我理解那将是很棒的!
此外,如果您发现某些编码实践不佳的东西,那么我是新手,并且正在寻求改进,因此欢迎您提供任何帮助。
编辑:哎呀,我忘记了从类内部复制和粘贴函数定义。他们在那里,但我仍然收到编译器错误。
//tamagotchi.cpp
#include "tamagotchi.h"
#include <string>
/* 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 <string>
class Tamagotchi
{
public:
/* 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();
private:
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 <string>
#include <iostream>
int main(){
Tamagotchi myTamagotchi;
std::cout << myTamagotchi.age();
return 0;
}
谢谢
最佳答案
您必须在类声明的头文件中声明访问器函数(或与此相关的任何成员函数):
class Tamagotchi
{
public:
/* initialization of default for tamagotchi */
Tamagotchi()
: myName ("Default"),
myAge ( 0 ),
myHappiness ( 0 ),
myHunger ( 0 ),
isSick ( false ) { }
private:
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
public:
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等)之类的简单事物和小型类的实例几乎可以免费按值返回。
关于c++ - 多个文件.h .cpp main.cpp的类用法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27035370/