c++ - 如何将 double vector 传递给构造函数,然后在子类中访问其数据(在 C++ 中)?

标签 c++ inheritance vector constructor

我不仅希望能够创建图表,还希望能够创建条形图,并传入 double vector 并将该数据放入私有(private)成员数据中。我将如何在图表的条形图(子)类中执行此操作?此外,我仍然对传递指针、引用或值感到困惑,所以我不确定我是否在这里正确传递了它。请让我知道如何解决这个问题。感谢您的帮助!

#include <vector>
using namespace std;
class Chart
{
  public:
    Chart(vector<double> &d) : data(d) {}
    virtual void draw() const;
  protected:
    double value_at(int index) const; // ... only allows access, not modification
    int get_size() const
    {
      return data.size();
    }
  private:
    vector<double> &data; // Now data is safely private
};

class BarChart : public Chart
{
  public:
    virtual void draw() const
    {
      for (int x = 0; x < get_size() - 1; x++)
      {
        cout << value_at(x) << " ";
        for (int y = 0; y < value_at(x); y++)
        {
          cout << "*";
        }
        cout << endl;
      }
    }
};

#include <iostream>
#include "chart.h"
#include <vector>    
int main(int argc, char** argv)
{
  vector<double> doubles;
  doubles.resize(4);
  for (int x = 0; x < 4; x++)
  {
    doubles[x] = x + 1.7;
  }
  BarChart c(doubles);
    return 0;
}

最佳答案

我想这就是你现在想要的。顺便说一句,你必须为你的 future 阅读这些东西:)

  1. 访问修饰符在继承中的作用
  2. 构造函数如何在继承中初始化
  3. 按引用传递和按值传递有什么区别。

这些都是你可以在互联网上阅读的。唯一需要花一些时间查找和阅读。

#include <vector>
#include <iostream>

class Chart
{
public:
    Chart(std::vector<double> &d) : data(d) {}
    virtual void draw(){}
    double value_at(int index) const{ return data[index];} 
    int get_size() const{return data.size();} 
private:
    std::vector<double> &data;
};

class BarChart : public Chart
{
public:
    BarChart(std::vector<double> &d):Chart(d)
    {
    }
    virtual void draw()
    {
        for (int x = 0; x < get_size() - 1; x++)
        {
            std::cout << value_at(x) << " ";
            for (int y = 0; y < value_at(x); y++)
            {
                std::cout << "*";
            }
            std::cout << std::endl;
        }
    }
};

int main()
{
    std::vector<double> barchartData;
    barchartData.push_back(10);
    barchartData.push_back(20);
    BarChart barchart(barchartData);
    std::cout << "Barchart size :" << barchart.get_size() << std::endl;

    std::vector<double> chartData;
    chartData.push_back(500);
    chartData.push_back(600);
    Chart chart(chartData);
    std::cout << "Chart size :" << chart.get_size() << std::endl;
    return 0;
}

关于c++ - 如何将 double vector 传递给构造函数,然后在子类中访问其数据(在 C++ 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24796351/

相关文章:

c++ - Arduino serial.available 奇怪的错误

c++ - 在神经网络上为Levenberg-Marquardt算法选择起始参数

c++ - 具有奇怪返回类型的结构

c++ - 以编程方式在默认浏览器中打开多个 URL

未找到 C++ 继承函数

c++ - 如何将文件读入元组 vector ?

c++ - Shared_ptr 没有可行的重载 '='

javascript - mixins 中的 prototype.js 实例属性

python - python中的向量矩阵乘法?

C++ vector 累加