作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何使 child 的数据成员可以在其父函数中看到并使用? (不使用虚拟)作业:我需要制作一个棋盘游戏类并派生一类黑白棋(任何大小的棋盘)。需要将打印板放在父类中。我坚持如何将电路板尺寸传递给父级以正确打印它。
#include <iostream>
using namespace std;
class Parent{
public:
void someFuc(){cout << person << endl;}
};
class Kid: public Parent{
private:
int person = 2;
};
int main()
{
Kid b = Kid();
b.someFuc(); // want it to print 2
return 0;
}
最佳答案
如果棋盘大小属于父级,则将其作为父级的成员,然后为子级提供一种通过构造函数或方法设置它的方法。
如果要强制子类在父类上设置棋盘大小,请为采用棋盘大小的父类创建一个 protected 构造函数,但不包括公共(public)构造函数。这可以防止基类被自己创建。它只能由必须提供板尺寸的派生类创建。
#include <iostream>
using namespace std;
class Parent{
protected:
Parent(int person)
{
m_person = person;
}
public:
void someFuc(){cout << person << endl;}
private:
int m_person;
};
class Kid: public Parent{
public:
Kid(int person) : Parent(person) {}
};
int main()
{
Kid b = Kid(2);
b.someFuc(); // want it to print 2
return 0;
}
关于C++ 继承 : How do you make it so that the kid's data member can be seen in its parent's functions and used?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23275605/
我是一名优秀的程序员,十分优秀!