获取我的基类以递增派生类对象整数
Get my base class to increment my derived class objects integer
在下面的代码中,我将如何让基类函数时钟::increment((函数在不修改main((的情况下递增派生的类对象thing2.hrs?如果我在 increment(( 中添加临时 cout 语句,如果我没有创建基对象,调用"thing2.increment(("似乎正在增加基类对象的成员或随机内存点。 在不修改 main(( 中的调用以传递变量(并修改函数(的情况下,是用派生类中的新定义覆盖函数的唯一解决方案吗?
class clocks
{
public:
clocks();
void increment();
private:
int hrs;
};
clocks::clocks()
{
hrs = 1;
}
void clocks::increment()
{
hrs++;
}
class childClock : public clocks
{
public:
childClock();
int hrs;
};
childClock::childClock()
{
hrs = 2;
}
int main()
{
clocks thing;
childClock thing2;
cout << thing2.hrs<<" ";
thing2.increment();
cout << thing2.hrs;
return 0;
}
几件事。
- 您不需要子类中的第二个
hrs
,因为基类已经声明了此成员。 hrs
应该受到保护,以便子类可以访问/设置它,并且您可以使用 getter 来访问该值。
按照这些说明,我们可以按如下方式编辑您的代码:
#include <iostream>
class clocks{
public:
clocks();
void increment();
int getHrs();
protected:
int hrs;
};
clocks::clocks(){
hrs = 1;
}
int clocks::getHrs(){
return hrs;
}
void clocks::increment(){
hrs++;
}
class childClock : public clocks{
public:
childClock();
};
childClock::childClock(){
hrs = 2;
}
int main(){
clocks thing;
childClock thing2;
std::cout << thing2.getHrs() <<" ";
thing2.increment();
std::cout << thing2.getHrs();
return 0;
}
相关文章:
- 为什么此派生对象无法访问基类的后递减方法?
- 如何在新的派生对象中获取基本对象的数据?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 在没有默认构造函数的情况下创建的派生对象
- OOP 标识派生对象
- 如何创建派生对象的向量?
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 如何从 Gtk::窗口调用派生对象的析构函数
- 无法在派生对象上运行虚拟函数
- 尝试删除指向派生对象的基指针时断言错误
- 存储在一个通用容器中的派生对象.如何避免铸造
- 将派生对象分配给函数内的基类指针
- 替换派生对象向量中的对象"no matching function to call"
- 派生对象调用的 Base 方法的模板推导
- 用于填充 Base 和派生对象的 shared_ptr 向量的函数模板
- C++ UBSAN 对派生对象产生误报
- 如何验证我是否正在使用C++中的基对象或派生对象
- C++ 构造函数和派生对象
- 将派生对象传递给模板
- 指向派生作品的基本指针,即使派生对象不存在