使用基类的C++和修改私有/受保护的属性

Using C++ and Modifying Private/Protected Attributes of a Base Class

本文关键字:受保护 属性 基类 C++ 修改      更新时间:2023-10-16

如果我问一些之前已经问过很多次的事情,我很抱歉。我对C++很陌生。我想知道如何使派生类继承其基类的私有属性的副本。要么,要么能够通过基类中的公共方法(例如getter和setter(修改它们。

本质上,我有一个 Person 类,它继承自 Creature 类。我希望 Person 类型对象具有类似于 Creature 类中的属性。我想将 Creature 类中的私有属性保持私有,因为我被教导只有类函数应该是公共的,而不是类变量。但是,我似乎无法在函数中调用 Creature 类的公共方法,并且 Person 类似乎没有继承它们或其副本。

我拒绝简单地公开私有属性的原因是因为我想学习正确的编程技术。我不确定这种情况是否是规则的例外。

我有处理实现的 cpp 文件。希望这足以帮助您回答我的问题。 我的基类:

/***
File: Creature.h
Desc: Contains Creature Class Definitions.
This is the base class for the Animal, Person, and PlayerCharacter classes.
Author: LuminousNutria
Date: 5-7-18
***/
#include <string>
#ifndef _CREATURE_H_
#define _CREATURE_H_
class Creature
{
private:
// General Information
std::string speciesName;
int hitpoints;
int movement;
// Physical Attributes
int strength;
int willpower;
int intelligence;
int leadership;
public:
// setters
void setSpeciesName(const std::string a);
void setHitpoints(const int a);
void setMovement(const int a);
void setStrength(const int a);
void setWillpower(const int a);
void setIntelligence(const int a);
void setLeadership(const int a);
// getters
std::string getSpeciesName();
int getHitpoints();
int getLoyalty();
int getMovement();
int getStrength();
int getWillpower();
int getIntelligence();
int getLeadership();
// modders
void modHitpoints(const int a);
void modMovement(const int a);
void modStrength(const int a);
void modWillpower(const int a);
void modIntelligence(const int a);
void modLeadership(const int a);
};

我的派生类:

/***
File: Person.h
Desc: Contains Person Class Definitions.
This is a derived class of the Creature class.
Author: LuminousNutria
Date: 5-7-18
***/

#include "Creature.h"
#include <string>
#ifndef _PERSON_H_
#define _PERSON_H_
class Person
{
protected:
std::string personName;
int loyalty;
int experience;
int level;
int cash;
public:
// constructors
Person();
Person(const std::string pName, const int loy, const int exp,
const int lvl, const int c,
const std::string sName, const int hp, const int mov,
const int stre, const int will, const int intl,
const int lead);
// setters
void setPersonName(std::string pName);
void setLoyalty(const int loy);
void setExperience(const int exp);
void setLevel(const int lvl);
void setCash(const int c);
// getters
std::string getPersonName();
int getLoyalty();
int getExperience();
int getLevel();
int getCash();
// modders
void modLoyalty(int a);
void modExperience(int a);
void modLevel(int a);
void modCash(int a);
};
#endif

生物类的 setSpeciesName 方法的实现:

void Creature::setSpeciesName(const std::string a)
{
speciesName = a;
}

在提供的代码中,Person不继承自Creature,因此它不继承 Creature 类的成员。

Person类定义为,以便它继承自Creature

class Person : public Creature
{
// same as before
};

有关公共继承与私有继承的更多详细信息,请参阅私有、公共和受保护继承之间的区别。通常你想要公共继承。

基本上有两种方法可以解决这个问题: 1. 将基构造函数显式调用到构造函数中。 2. 使用友元运算符使用私有元素。