gpt4 book ai didi

C++ 继承 : How do you make it so that the kid's data member can be seen in its parent's functions and used?

转载 作者:行者123 更新时间:2023-11-28 06:55:12 25 4
gpt4 key购买 nike

如何使 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com