我希望不仅能够创建一个图表,而且能够创建一个BarChart,并传入一个双精度体向量,并将该数据放入私有成员data中。我如何在Chart的BarChart(子)类中做到这一点?此外,我仍然感到困惑,通过指针,引用或值传递,所以我不确定我是否在这里正确传递它。请让我知道如何解决这个烂摊子。谢谢你的帮助!
#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;
}
我想这就是你现在想要的。顺便说一下,你必须为你的未来读这些东西:)
- 访问修饰符如何在继承中工作
- 构造函数如何初始化继承
- 按引用传递和按值传递有什么区别
这些都是你能在网上读到的。唯一需要做的就是花点时间查找和阅读。
#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;
}