【问题标题】:Is there any way that data can be inherited from one class to another?有什么方法可以将数据从一个类继承到另一个类?
【发布时间】:2021-12-05 10:31:36
【问题描述】:

我正在尝试学习面向对象编程,但遇到了一个问题。我有两个班级AB。我将命令行参数传递给类A,然后执行一些计算并形成一个二维向量。 (让我们将向量称为data

我希望 B 类继承 A 类。

所以我想知道有什么方法可以在调用B 类的默认构造函数时打印二维向量data 的内容。

我尝试过的示例代码

class A
{
        
    public:
        vector<vector<string>>data;
        fstream file;
        string word, filename;
        A()
        {

        }
        A(string fileOpen)
        {
            file.open(fileOpen);
            while (file >> word)
            {
                
                vector<string>rowTemp={word};
                data.push_back(rowTemp);
            }
        }
        vector<vector<string>> getVector()
        {
            return data;
        }
};

class B:A
{
    public:
        B()
        {
            for(auto i:data)
            {
                for(auto j:i)
                {
                    cout<<j<<' ';
                }
                cout<<endl;
            }
        }
};

int main(int argc, char* argv[]){
 
    fstream file;
    string word, filename;
 
    file.open(argv[1]);
    string fileOpen=argv[1];

    A s(fileOpen);
    B c;
    return 0;
}

我基本上希望 B 类能够访问二维向量 data,以便我可以对其执行进一步的计算,而计算逻辑仍保留在 B 类中。

有没有办法做到这一点?

此外,正如您在 A 类中看到的,默认构造函数是空的。但它是必需的,因为没有它,我收到一个错误,即无法调用类 B 的默认构造函数。有没有更好的方法来写这个?因为有一个空的默认构造函数看起来很糟糕。

【问题讨论】:

  • 请发帖minimal reproducible example。您可以删除文件读取,因为这对问题不是必需的,但会阻止其他人运行您的代码
  • 您希望B c; 访问A s(fileOpen); 的成员吗?它们是两个不相关的对象
  • 就像class 的成员访问默认为private,继承也是如此。如果要访问父级的公共成员,则需要 public 继承。如class B : public A
  • 澄清一下,当你有类 A 和 B,并且 B 从 A 继承时,你(通常)没有显式的 A 实例,只有一个 B 实例,作为它有一个 A 的“嵌入式”实例。
  • 听起来你把类和对象混淆了。

标签: c++ class oop inheritance


【解决方案1】:

您似乎误解了继承的工作原理,只是不清楚您的期望。问题是:基类的成员总是被继承的。他们的访问权限可能会受到限制,但他们仍然存在。

考虑这个简化的例子:

#include <iostream>

class A {
        
    public:
        int data = 42;
        A() = default;
        A(int value) : data(value) {}
        int getData() { return data; }
};

class B : A {
    public:
        B() {
            std::cout << A::data;         // ok
            std::cout << A::getData();    // ok
        }
};

int main(){ 
    B c;
    //std::cout << c.data; // error: data is private!
}

输出是:

4242

因为B 确实从A 继承了data 成员。在B 中,您可以直接或通过getData 访问data,因为两者都是public 中的A。但是,因为B 是从A 私下继承的(这是通过class 定义的类的默认继承),所以您不能直接访问main 中的datagetData

此外,当你写作时:

A s(fileOpen);
B c;

那么sc 是两个完全不相关的对象。我想你更愿意:

B c{fileOpen};

并从B的构造函数中调用As的构造函数:

B(const std::string& filename) : A(filename) {
     // now you can access A::data 
     // which has been initialized in 
     // constructor of A
}

【讨论】:

  • 非常感谢您的回答!这正是我想要的。我不知道可以这样调用构造函数。非常感谢。
  • 只是为了确认,在B(const std::string&amp; filename) : A(filename)中,B的参数是从A类继承的?
  • @alexderalu 将参数传递给Bs 构造函数,filename,转发给As 构造函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 2023-01-24
  • 1970-01-01
相关资源
最近更新 更多