【问题标题】:A class One with data members int a and char b inherits from another class Two with data members float f and int x具有数据成员 int a 和 char b 的类 One 从另一个具有数据成员 float f 和 int x 的类继承
【发布时间】:2022-01-08 17:09:09
【问题描述】:

我需要类一和二的类定义,其中: 1。这两个类的对象都能够访问这两个类的所有数据成员。 2。只有类 One 的成员可以访问这两个类的所有数据成员。

//case 2
#include <iostream>
using namespace std;

class Two{
    public:
        float f;
        int x;
};

class One: public Two{
    private:
        int a;
        char b;
};

我已经尝试了第二部分。这是正确的吗?你能帮我完成第一部分吗?

【问题讨论】:

标签: c++ c++11


【解决方案1】:

我不确定,你到底想要什么。你可以通过继承来做到这一点。 我建议您阅读一些有关此的教程,例如 https://www.tutorialspoint.com/cplusplus/cpp_inheritance.htmhttps://www.geeksforgeeks.org/inheritance-in-c/

您可以轻松地尝试它是否正确;只需编译它,看看发生了什么。

2:

#include <iostream>
using namespace std;

// Your classes go here


int main()
{
    One o;
    o.f= 1;
    o.x= 2;
    o.a = 10;
    o.b = 11;

    Two t;
    t.f= 21;
    t.x = 22;

    cout << "One: f: " << o.f << endl;
    cout << "One: x: " << o.x << endl;
    // and so on

    return 0;
}

对于第一部分,考虑为 one 和 two 都创建一个基类,以存储两个子类都可以访问的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 2015-11-01
    • 2011-02-07
    • 2020-10-21
    • 2020-07-10
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多