I have this class (full code) in Screen.h:
#include <string>
#include <iostream>
class Screen {
using pos = std::string::size_type;
private:
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
public:
Screen() = default; // needed because Screen has another constructor
Screen(pos ht, pos wd) : Screen(ht, wd, ' ') {}
Screen(pos ht, pos wd, char c): height(ht), width(wd),
contents(ht * wd, c) { }
char get() const {
return contents[cursor];
}
Screen& move(pos r, pos c);
inline char get(pos ht, pos wd) const; // explicitly inline
Screen& set(char);
const Screen& display(std::ostream&) const;
Screen& display(std::ostream&);
private:
void doDisplay(std::ostream&) const;
};
and the implementation for it in Screen.cpp:
#include "Screen.h"
#include <iostream>
char Screen::get(pos r, pos c) const // declared as inline in the class
{
pos row = r * width; // compute row location
return contents[row + c]; // return character at the given column
}
inline Screen& Screen::move(pos r, pos c) {
pos row = r * width;
cursor = row + c;
return *this;
}
Screen& Screen::set(char c) {
contents[cursor] = c;
return *this;
}
Screen& Screen::display(std::ostream& outputStream) {
doDisplay(outputStream);
return *this;
}
const Screen& Screen::display(std::ostream& outputStream) const {
doDisplay(outputStream);
return *this;
}
void Screen::doDisplay(std::ostream& outputStream) const {
for (unsigned h = 0; h < height; ++h) {
for (unsigned w = 0; w < width; ++w) {
outputStream << contents[h*w];
}
outputStream << std::endl;
}
}
My main file:
#include "Screen.h"
#include <iostream>
int main() {
Screen myScreen(5, 5, 'X');
myScreen.move(0,4).set('#').display(std::cout);
std::cout << std::endl;
int returnCode = EXIT_SUCCESS;
return returnCode;
}
this produces the following linker error: undefined reference to `Screen::move(unsigned long long, unsigned long long)'
When I remove the "inline" from Screen::move, it works, but somehow the char at 0,4 doesn't get changed... I don't really know what's not working. I'm using Code::Blocks with the gcc compiler.
Edit: okay everything works fine when I remove the "inline" from the definition of the "move" method. But now my question is: why can't I specify "inline" in Screen.cpp?
You have inline in cpp file remove inline and it will be fine. I mean for the Screen::move function. Alternative move definition to header file.
Put it into *.h or make it private and use it in *cpp, exclusively.
Related
I've been pulling my hair out over a certain error that seems to be plaguing my program. I've attempted to search online for cases similar to mine but I can't seem to find a way to apply the other solutions to this problem. My issue is as follows: When I initially open the program it immediately stops responding and crashes. Debugging led me to find the error in question is "0xC0000005: Access violation writing location 0xCCCCCCCC". It seems to be tied to me assigning two attributes (sku_ and name_ ) as '\0'. If I change these values to anything else such as "" or even "\0" the program runs in visual studio, but will fail to compile elsewhere. Could someone help me understand where I am going wrong?
Product.h
#ifndef SICT_Product_H__
#define SICT_Product_H__
#include "general.h"
#include "Streamable.h"
#include <cstring>
namespace sict {
class Product : public Streamable {
char sku_ [MAX_SKU_LEN + 1];
char* name_;
double price_;
bool taxed_;
int quantity_;
int qtyNeeded_;
public:
//Constructors
Product();
Product(const char* sku, const char* name1, bool taxed = true, double price = 0, int qtyNeeded =0);
Product(Product& g);
~Product();
//Putter Functions
void sku(const char* sku) { strcpy(sku_,sku); };
void price(double price) {price_ = price;};
void name(const char* name);
void taxed(bool taxed) { taxed_ = taxed; };
void quantity(int quantity) { quantity_ = quantity; };
void qtyNeeded(int qtyNeeded) { qtyNeeded_ = qtyNeeded; };
//Getter functions
const char* sku() const { return sku_; };
double price() const { return price_; };
const char* name() const { return name_; };
bool taxed() const { return taxed_; };
int quantity() const { return quantity_; };
int qtyNeeded() const { return qtyNeeded_; };
double cost() const;
bool isEmpty() const;
Product& operator=(const Product& );
bool operator==(const char* );
int operator+=(int );
int operator-=(int );
};
double operator+=(double& , const Product& );
std::ostream& operator<<(std::ostream& os, const Product& );
std::istream& operator>>(std::istream& is, Product& );
}
#endif
Product.cpp
#include <iostream>
#include <cstring>
#include "Product.h"
namespace sict {
Product::Product() {
sku_[0] = '\0';
name_[0] = '\0';
price_ = 0;
quantity_ = 0;
qtyNeeded_ = 0;
}
Product::Product(const char* sku, const char* name1, bool taxed1, double price1, int qtyNeeded1) {
strncpy(sku_, sku, MAX_SKU_LEN);
name(name1);
quantity_ = 0;
taxed(taxed1);
price(price1);
qtyNeeded(qtyNeeded1);
}
double Product::cost() const {
if (taxed_ == true) {
return (price_ * TAX) + price_;
}
else
return price_;
}
bool Product::isEmpty() const{
if (sku_ == nullptr && name_ == nullptr && quantity_ == 0 && price_ == 0 && qtyNeeded_ == 0) {
return true;
}
else
return false;
}
Product::Product(Product& ex) {
sku(ex.sku_);
price(ex.price_);
name(ex.name_);
taxed(ex.taxed_);
quantity(ex.quantity_);
qtyNeeded(ex.qtyNeeded_);
}
Product& Product::operator=(const Product& g) {
sku(g.sku_);
price(g.price_);
name(g.name_);
taxed(g.taxed_);
quantity(g.quantity_);
qtyNeeded(g.qtyNeeded_);
return *this;
}
Product::~Product() {
delete [] name_;
}
void Product::name(const char* name) {
name_ = new char [strlen(name) + 1];
strcpy(name_, name);
}
bool Product::operator==(const char* right) {
if (sku_ == right) {
return true;
}
else
return false;
}
int Product::operator+=(int g) {
quantity_ = quantity_ + g;
return quantity_;
}
int Product::operator-=(int g) {
quantity_ = quantity_ - g;
return quantity_;
}
double operator+=(double& p, const Product& right) {
p = p + (right.cost() * right.quantity());
return p;
}
std::ostream& operator<<(std::ostream& os, const Product& g) {
return g.write(os, true);
}
std::istream& operator>>(std::istream& is, Product& g) {
return g.read(is);
}
}
The General.h file referenced in the header is just a list of constant values such as the "TAX" and "MAX_SKU_LEN" values.
The Streamable header contains pure virtual functions. I will list it here in case it is needed.
Streamable.h
#ifndef SICT__Streamable_H_
#define SICT__Streamable_H_
#include <iostream>
#include <fstream>
#include "Product.h"
namespace sict {
class Streamable {
public:
virtual std::fstream& store(std::fstream& file, bool addNewLine = true)const = 0;
virtual std::fstream& load(std::fstream& file) = 0;
virtual std::ostream& write(std::ostream& os, bool linear)const = 0;
virtual std::istream& read(std::istream& is) = 0;
};
}
#endif
Thank you very much in advance.
Product::Product() {
sku_[0] = '\0';
name_[0] = '\0'; // <---- writing via unitialized pointer
price_ = 0;
quantity_ = 0;
qtyNeeded_ = 0;
}
There's one possible source of your problems. You have defined a char pointer (a dynamic array or a C-string, that is) name_ in your class but you never allocate any memory for it in your constructor, before attempting to record a value via the pointer. Naturally, you get a write access violation.
Before assigning the value to char at index [0] you need to first allocate space for at least one element in your string, e.g. by doing name_ = new char [1]. Alternatively, you may choose to initialize the pointer itself to NULL (or nullptr) and use that to indicate that name_ has not yet been set.
I write a small animation program with OpenSceneGraph(osg). In each frame, I should update the models(vertex position,normal, color and other stuff) in the scene.
Now I shoudl convert the data to osg in each frame. The code is like:
cog_.vertex_->clear();
cog_.vertex_->push_back(osg::Vec3(1.0,1.0,1.0));
However these convertion is very time consuming. So I'm wondering how to access data directly via pointer. I tried but failed. The following is what I did, hope someone can help me to find the problem, or tell me better solution:
First, I wrap the a pointer to osg::Vec3,
class vec3_map : public osg::Vec3
{
public:
typedef osg::Vec3::value_type value_type;
osg::Vec3::value_type* p_;
vec3_map() :p_(0) {}
vec3_map(osg::Vec3::value_type*p, int offset = 0) :p_(p+offset){}
inline value_type& x() { return *(p_+0); }
inline value_type& y() { return *(p_+1); }
inline value_type& z() { return *(p_+2); }
// some other stuff
};
When I want to build an array of vec3_map, I found that osg use a tempalte to typedef Vec3Array, but there isn't any type for a pointer, so I choose the closet one (I know pointer is a variable with unsigned long int type):
typedef osg::TemplateArray<vec3_map, osg::Array::UIntArrayType, 1, GL_UNSIGNED_INT> Vec3_map_Array;
With this definition, I can rewrite my problem to the following:
#define BOOST_ALL_NO_LIB
#include <boost/shared_ptr.hpp>
#include <fstream>
#include <vector>
#include <osg/Group>
#include <osg/Geometry>
#include <osgViewer/Viewer>
#include <osg/Vec3>
class vec3_map : public osg::Vec3
{
public:
typedef osg::Vec3::value_type value_type;
osg::Vec3::value_type* p_;
vec3_map() :p_(0) {}
vec3_map(osg::Vec3::value_type*p, int offset = 0) :p_(p + offset) {}
inline value_type* ptr() { return p_; }
inline const value_type* ptr() const { return p_; }
inline value_type& operator [] (int i) { return *(p_ + i); }
inline value_type operator [] (int i) const { return *(p_ + i); }
inline value_type& x() { return *(p_ + 0); }
inline value_type& y() { return *(p_ + 1); }
inline value_type& z() { return *(p_ + 2); }
inline value_type x() const { return *(p_); }
inline value_type y() const { return *(p_ + 1); }
inline value_type z() const { return *(p_ + 2); }
};
typedef osg::TemplateArray<vec3_map, osg::Array::UIntArrayType, 1, GL_UNSIGNED_INT> Vec3_map_Array;
struct point_data
{
point_data(float xx, float yy, float zz) { x = xx; y = yy; z = zz; }
float x;
float y;
float z;
};
osg::Geode* create_point_node(boost::shared_ptr<std::vector<point_data> > ptr)
{
osg::Geode *geode_ = new osg::Geode;
osg::Geometry* geometry_ = new osg::Geometry;
Vec3_map_Array* vertex_ = new Vec3_map_Array;
osg::DrawElementsUInt* point_idx_ = new osg::DrawElementsUInt;
vertex_->reserve(ptr->size());
point_idx_->reserve(ptr->size());
vec3_map vm;
std::vector<point_data> & pd = *ptr;
for (size_t i = 0; i < ptr->size(); ++i)
{
vertex_->push_back(vec3_map(&(pd[i].x)));
point_idx_->push_back(i);
}
geometry_->setVertexArray(vertex_);
geometry_->addPrimitiveSet(point_idx_);
geode_->addDrawable(geometry_);
return geode_;
}
int main(int argc, char *argv[])
{
boost::shared_ptr<std::vector<point_data> > pd(new std::vector<point_data>);
pd->push_back(point_data(1.0, 1.0, 1.0));
pd->push_back(point_data(2.0, 2.0, 2.0));
osgViewer::Viewer viewer;
osg::Node *node = create_point_node(pd);
viewer.setSceneData(node);
return viewer.run();
}
However, this problem crashes. I'm not sure whether I can do something like this.
Is there a way to apply the shader in plugin?
I'm trying to implement anti-aliasing, but all my attempts failed :\
Use this simple:
#include <fstream>
#include <sstream>
#include "DDImage/Knobs.h"
#include "DDImage/DDMath.h"
#include "DDImage/ViewerContext.h"
#include "DDImage/Iop.h"
#include "DDImage/PixelIop.h"
#include "DDImage/Row.h"
using namespace DD::Image;
////////////////////////////////////////////////////////////////
/// GPU File Shader Op.
class GPUFileShader : public DD::Image::PixelIop
{
const char* shaderFile_;
std::string currShaderFile_;
std::string shader_;
int version_;
int currVersion_;
const char* gpuEngine_body() const
{
return shader_.c_str();
}
void pixel_engine(const Row& in, int y, int x, int r, ChannelMask channels, Row& out)
{
foreach(z, channels) {
const float* inptr = in[z] + x;
const float* END = inptr + (r - x);
float* outptr = out.writable(z) + x;
while (inptr < END)
*outptr++ = *inptr++;
}
}
void in_channels(int, DD::Image::ChannelSet& c) const { } // return c unchanged
public:
GPUFileShader(Node* node)
: PixelIop(node)
, shaderFile_(0)
, version_(0)
, currVersion_(0)
{ }
void knobs(Knob_Callback f)
{
File_knob(f, &shaderFile_, "shader_file", "OpenGL Shading Language file");
}
void _validate(bool)
{
if (!shaderFile_)
return;
if (version_ != currVersion_ || currShaderFile_ != std::string(shaderFile_)) {
std::ifstream ifs(shaderFile_);
if (!ifs) {
Iop::error("Error reading shader file.");
return;
}
std::stringstream str;
std::copy(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(str));
shader_ = str.str();
currVersion_ = version_;
currShaderFile_.assign(shaderFile_);
}
copy_info(0);
}
static const DD::Image::Op::Description d;
const char* Class() const { return d.name; }
const char* node_help() const { return "GPU Op which gets initialised from a file. Customise for proprietary formats. Default assumes OpenGL shading language code."; }
};
static Op* GPUFileShader_c(Node* node) { return new GPUFileShader(node); }
const Op::Description GPUFileShader::d("GPUFileShader", GPUFileShader_c);
I have successfully installed FLTK in VS 2015 Community Edition. I am dealing with other headers, part of Stroustrup's book, to build graphs and to create custom windows where to attach them. My problem is that when I am trying to compile I receive 4 error messagges (plus 23 Warnings):
(active) IntelliSense namespace "std" has no member
"Vector" Win32Project1 c:\Users\Leonardo\Documents\Visual Studio
2015\Projects\Win32Project1\Win32Project1\Window.h 17
Error C2873 Build 'Vector': symbol cannot be used in a
using-declaration Win32Project1 c:\users\leonardo\documents\visual
studio 2015\projects\win32project1\win32project1\Window.h 17
Error C2039 Build 'Vector': is not a member of
'std' Win32Project1 c:\users\leonardo\documents\visual studio
2015\projects\win32project1\win32project1\Window.h 17
Error C2440 Build 'return': cannot convert from 'std::ifstream' to
'bool' Win32Project1 C:\Users\Leonardo\Documents\Visual Studio
2015\Projects\Win32Project1\Win32Project1\Graph.cpp 371
I have set a Win32Project (not a Console Project), following the steps of this site: http://www.c-jump.com/bcc/common/Talk2/Cxx/FltkInstallVC/FltkInstallVC.html.
If I run the test example it perfectly works so, I guess, to have correctly installed the additional library.
Furthermore, I have added every header or source file provided by the author in the project.
main.cpp:
#include "std_lib_facilities.h"
#include "Graph.h"
#include "Simple_window.h"
int main()
{
using namespace Graph_lib;
Point tl{ 100,100 };
Simple_window win{ tl,600,400,"My Window" };
win.wait_for_button();
}
All headers and source file can be reached at: http://www.stroustrup.com/Programming/Programming-code.zip
Here Windows.h
//
// This is a GUI support code to the chapters 12-16 of the book
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
#ifndef WINDOW_GUARD
#define WINDOW_GUARD
#include <string>
#include <vector>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include "Point.h"
using std::string;
using std::vector;
namespace Graph_lib
{
class Shape; // "forward declare" Shape
class Widget;
//------------------------------------------------------------------------------
class Window : public Fl_Window {
public:
// let the system pick the location:
Window(int w, int h, const string& title);
// top left corner in xy
Window(Point xy, int w, int h, const string& title);
virtual ~Window() { }
int x_max() const { return w; }
int y_max() const { return h; }
void resize(int ww, int hh) { w=ww, h=hh; size(ww,hh); }
void set_label(const string& s) { copy_label(s.c_str()); }
void attach(Shape& s) { shapes.push_back(&s); }
void attach(Widget&);
void detach(Shape& s); // remove s from shapes
void detach(Widget& w); // remove w from window (deactivates callbacks)
void put_on_top(Shape& p); // put p on top of other shapes
protected:
void draw();
private:
vector<Shape*> shapes; // shapes attached to window
int w,h; // window size
void init();
};
and Graph.cpp
//
// This is a GUI support code to the chapters 12-16 of the book
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
#include <FL/Fl_GIF_Image.H>
#include <FL/Fl_JPEG_Image.H>
#include "Graph.h"
//------------------------------------------------------------------------------
namespace Graph_lib {
//------------------------------------------------------------------------------
Shape::Shape() :
lcolor(fl_color()), // default color for lines and characters
ls(0), // default style
fcolor(Color::invisible) // no fill
{}
//------------------------------------------------------------------------------
void Shape::add(Point p) // protected
{
points.push_back(p);
}
//------------------------------------------------------------------------------
void Shape::set_point(int i,Point p) // not used; not necessary so far
{
points[i] = p;
}
//------------------------------------------------------------------------------
void Shape::draw_lines() const
{
if (color().visibility() && 1<points.size()) // draw sole pixel?
for (unsigned int i=1; i<points.size(); ++i)
fl_line(points[i-1].x,points[i-1].y,points[i].x,points[i].y);
}
//------------------------------------------------------------------------------
void Shape::draw() const
{
Fl_Color oldc = fl_color();
// there is no good portable way of retrieving the current style
fl_color(lcolor.as_int()); // set color
fl_line_style(ls.style(),ls.width()); // set style
draw_lines();
fl_color(oldc); // reset color (to previous)
fl_line_style(0); // reset line style to default
}
//------------------------------------------------------------------------------
void Shape::move(int dx, int dy) // move the shape +=dx and +=dy
{
for (int i = 0; i<points.size(); ++i) {
points[i].x+=dx;
points[i].y+=dy;
}
}
//------------------------------------------------------------------------------
Line::Line(Point p1, Point p2) // construct a line from two points
{
add(p1); // add p1 to this shape
add(p2); // add p2 to this shape
}
//------------------------------------------------------------------------------
void Lines::add(Point p1, Point p2)
{
Shape::add(p1);
Shape::add(p2);
}
//------------------------------------------------------------------------------
// draw lines connecting pairs of points
void Lines::draw_lines() const
{
if (color().visibility())
for (int i=1; i<number_of_points(); i+=2)
fl_line(point(i-1).x,point(i-1).y,point(i).x,point(i).y);
}
//------------------------------------------------------------------------------
// does two lines (p1,p2) and (p3,p4) intersect?
// if se return the distance of the intersect point as distances from p1
inline pair<double,double> line_intersect(Point p1, Point p2, Point p3, Point p4, bool& parallel)
{
double x1 = p1.x;
double x2 = p2.x;
double x3 = p3.x;
double x4 = p4.x;
double y1 = p1.y;
double y2 = p2.y;
double y3 = p3.y;
double y4 = p4.y;
double denom = ((y4 - y3)*(x2-x1) - (x4-x3)*(y2-y1));
if (denom == 0){
parallel= true;
return pair<double,double>(0,0);
}
parallel = false;
return pair<double,double>( ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3))/denom,
((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3))/denom);
}
//------------------------------------------------------------------------------
//intersection between two line segments
//Returns true if the two segments intersect,
//in which case intersection is set to the point of intersection
bool line_segment_intersect(Point p1, Point p2, Point p3, Point p4, Point& intersection){
bool parallel;
pair<double,double> u = line_intersect(p1,p2,p3,p4,parallel);
if (parallel || u.first < 0 || u.first > 1 || u.second < 0 || u.second > 1) return false;
intersection.x = p1.x + u.first*(p2.x - p1.x);
intersection.y = p1.y + u.first*(p2.y - p1.y);
return true;
}
//------------------------------------------------------------------------------
void Polygon::add(Point p)
{
int np = number_of_points();
if (1<np) { // check that thenew line isn't parallel to the previous one
if (p==point(np-1)) error("polygon point equal to previous point");
bool parallel;
line_intersect(point(np-1),p,point(np-2),point(np-1),parallel);
if (parallel)
error("two polygon points lie in a straight line");
}
for (int i = 1; i<np-1; ++i) { // check that new segment doesn't interset and old point
Point ignore(0,0);
if (line_segment_intersect(point(np-1),p,point(i-1),point(i),ignore))
error("intersect in polygon");
}
Closed_polyline::add(p);
}
//------------------------------------------------------------------------------
void Polygon::draw_lines() const
{
if (number_of_points() < 3) error("less than 3 points in a Polygon");
Closed_polyline::draw_lines();
}
//------------------------------------------------------------------------------
void Open_polyline::draw_lines() const
{
if (fill_color().visibility()) {
fl_color(fill_color().as_int());
fl_begin_complex_polygon();
for(int i=0; i<number_of_points(); ++i){
fl_vertex(point(i).x, point(i).y);
}
fl_end_complex_polygon();
fl_color(color().as_int()); // reset color
}
if (color().visibility())
Shape::draw_lines();
}
//------------------------------------------------------------------------------
void Closed_polyline::draw_lines() const
{
Open_polyline::draw_lines(); // first draw the "open poly line part"
// then draw closing line:
if (color().visibility())
fl_line(point(number_of_points()-1).x,
point(number_of_points()-1).y,
point(0).x,
point(0).y);
}
//------------------------------------------------------------------------------
void draw_mark(Point xy, char c)
{
static const int dx = 4;
static const int dy = 4;
string m(1,c);
fl_draw(m.c_str(),xy.x-dx,xy.y+dy);
}
//------------------------------------------------------------------------------
void Marked_polyline::draw_lines() const
{
Open_polyline::draw_lines();
for (int i=0; i<number_of_points(); ++i)
draw_mark(point(i),mark[i%mark.size()]);
}
//------------------------------------------------------------------------------
void Rectangle::draw_lines() const
{
if (fill_color().visibility()) { // fill
fl_color(fill_color().as_int());
fl_rectf(point(0).x,point(0).y,w,h);
}
if (color().visibility()) { // lines on top of fill
fl_color(color().as_int());
fl_rect(point(0).x,point(0).y,w,h);
}
}
//------------------------------------------------------------------------------
Circle::Circle(Point p, int rr) // center and radius
:r(rr)
{
add(Point(p.x-r,p.y-r)); // store top-left corner
}
//------------------------------------------------------------------------------
Point Circle::center() const
{
return Point(point(0).x+r, point(0).y+r);
}
//------------------------------------------------------------------------------
void Circle::draw_lines() const
{
if (color().visibility())
fl_arc(point(0).x,point(0).y,r+r,r+r,0,360);
}
//------------------------------------------------------------------------------
void Ellipse::draw_lines() const
{
if (color().visibility())
fl_arc(point(0).x,point(0).y,w+w,h+h,0,360);
}
//------------------------------------------------------------------------------
void Text::draw_lines() const
{
int ofnt = fl_font();
int osz = fl_size();
fl_font(fnt.as_int(),fnt_sz);
fl_draw(lab.c_str(),point(0).x,point(0).y);
fl_font(ofnt,osz);
}
//------------------------------------------------------------------------------
Axis::Axis(Orientation d, Point xy, int length, int n, string lab) :
label(Point(0,0),lab)
{
if (length<0) error("bad axis length");
switch (d){
case Axis::x:
{
Shape::add(xy); // axis line
Shape::add(Point(xy.x+length,xy.y));
if (1<n) { // add notches
int dist = length/n;
int x = xy.x+dist;
for (int i = 0; i<n; ++i) {
notches.add(Point(x,xy.y),Point(x,xy.y-5));
x += dist;
}
}
// label under the line
label.move(length/3,xy.y+20);
break;
}
case Axis::y:
{
Shape::add(xy); // a y-axis goes up
Shape::add(Point(xy.x,xy.y-length));
if (1<n) { // add notches
int dist = length/n;
int y = xy.y-dist;
for (int i = 0; i<n; ++i) {
notches.add(Point(xy.x,y),Point(xy.x+5,y));
y -= dist;
}
}
// label at top
label.move(xy.x-10,xy.y-length-10);
break;
}
case Axis::z:
error("z axis not implemented");
}
}
//------------------------------------------------------------------------------
void Axis::draw_lines() const
{
Shape::draw_lines();
notches.draw(); // the notches may have a different color from the line
label.draw(); // the label may have a different color from the line
}
//------------------------------------------------------------------------------
void Axis::set_color(Color c)
{
Shape::set_color(c);
notches.set_color(c);
label.set_color(c);
}
//------------------------------------------------------------------------------
void Axis::move(int dx, int dy)
{
Shape::move(dx,dy);
notches.move(dx,dy);
label.move(dx,dy);
}
//------------------------------------------------------------------------------
Function::Function(Fct f, double r1, double r2, Point xy,
int count, double xscale, double yscale)
// graph f(x) for x in [r1:r2) using count line segments with (0,0) displayed at xy
// x coordinates are scaled by xscale and y coordinates scaled by yscale
{
if (r2-r1<=0) error("bad graphing range");
if (count <=0) error("non-positive graphing count");
double dist = (r2-r1)/count;
double r = r1;
for (int i = 0; i<count; ++i) {
add(Point(xy.x+int(r*xscale),xy.y-int(f(r)*yscale)));
r += dist;
}
}
//------------------------------------------------------------------------------
bool can_open(const string& s)
// check if a file named s exists and can be opened for reading
{
ifstream ff(s.c_str());
return ff;
}
//------------------------------------------------------------------------------
#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
Suffix::Encoding get_encoding(const string& s)
{
struct SuffixMap
{
const char* extension;
Suffix::Encoding suffix;
};
static SuffixMap smap[] = {
{".jpg", Suffix::jpg},
{".jpeg", Suffix::jpg},
{".gif", Suffix::gif},
};
for (int i = 0, n = ARRAY_SIZE(smap); i < n; i++)
{
int len = strlen(smap[i].extension);
if (s.length() >= len && s.substr(s.length()-len, len) == smap[i].extension)
return smap[i].suffix;
}
return Suffix::none;
}
//------------------------------------------------------------------------------
// somewhat over-elaborate constructor
// because errors related to image files can be such a pain to debug
Image::Image(Point xy, string s, Suffix::Encoding e)
:w(0), h(0), fn(xy,"")
{
add(xy);
if (!can_open(s)) { // can we open s?
fn.set_label("cannot open \""+s+'\"');
p = new Bad_image(30,20); // the "error image"
return;
}
if (e == Suffix::none) e = get_encoding(s);
switch(e) { // check if it is a known encoding
case Suffix::jpg:
p = new Fl_JPEG_Image(s.c_str());
break;
case Suffix::gif:
p = new Fl_GIF_Image(s.c_str());
break;
default: // Unsupported image encoding
fn.set_label("unsupported file type \""+s+'\"');
p = new Bad_image(30,20); // the "error image"
}
}
//------------------------------------------------------------------------------
void Image::draw_lines() const
{
if (fn.label()!="") fn.draw_lines();
if (w&&h)
p->draw(point(0).x,point(0).y,w,h,cx,cy);
else
p->draw(point(0).x,point(0).y);
}
//------------------------------------------------------------------------------
} // of namespace Graph_lib
I hope someone could help me.
EDIT
/*
std_lib_facilities.h
*/
/*
simple "Programming: Principles and Practice using C++ (second edition)" course header to
be used for the first few weeks.
It provides the most common standard headers (in the global namespace)
and minimal exception/error support.
Students: please don't try to understand the details of headers just yet.
All will be explained. This header is primarily used so that you don't have
to understand every concept all at once.
By Chapter 10, you don't need this file and after Chapter 21, you'll understand it
Revised April 25, 2010: simple_error() added
Revised November 25 2013: remove support for pre-C++11 compilers, use C++11: <chrono>
Revised November 28 2013: add a few container algorithms
Revised June 8 2014: added #ifndef to workaround Microsoft C++11 weakness
*/
#ifndef H112
#define H112 251113L
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
typedef long Unicode;
//------------------------------------------------------------------------------
using namespace std;
template<class T> string to_string(const T& t)
{
ostringstream os;
os << t;
return os.str();
}
struct Range_error : out_of_range { // enhanced vector range error reporting
int index;
Range_error(int i) :out_of_range("Range error: "+to_string(i)), index(i) { }
};
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
using size_type = typename std::vector<T>::size_type;
#ifdef _MSC_VER
// microsoft doesn't yet support C++11 inheriting constructors
Vector() { }
explicit Vector(size_type n) :std::vector<T>(n) {}
Vector(size_type n, const T& v) :std::vector<T>(n,v) {}
template <class I>
Vector(I first, I last) : std::vector<T>(first, last) {}
Vector(initializer_list<T> list) : std::vector<T>(list) {}
#else
using std::vector<T>::vector; // inheriting constructor
#endif
T& operator[](unsigned int i) // rather than return at(i);
{
if (i<0||this->size()<=i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
const T& operator[](unsigned int i) const
{
if (i<0||this->size()<=i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
};
// disgusting macro hack to get a range checked vector:
#define vector Vector
// trivially range-checked string (no iterator checking):
struct String : std::string {
using size_type = std::string::size_type;
// using string::string;
char& operator[](unsigned int i) // rather than return at(i);
{
if (i<0||size()<=i) throw Range_error(i);
return std::string::operator[](i);
}
const char& operator[](unsigned int i) const
{
if (i<0||size()<=i) throw Range_error(i);
return std::string::operator[](i);
}
};
namespace std {
template<> struct hash<String>
{
size_t operator()(const String& s) const
{
return hash<std::string>()(s);
}
};
} // of namespace std
struct Exit : runtime_error {
Exit(): runtime_error("Exit") {}
};
// error() simply disguises throws:
inline void error(const string& s)
{
throw runtime_error(s);
}
inline void error(const string& s, const string& s2)
{
error(s+s2);
}
inline void error(const string& s, int i)
{
ostringstream os;
os << s <<": " << i;
error(os.str());
}
template<class T> char* as_bytes(T& i) // needed for binary I/O
{
void* addr = &i; // get the address of the first byte
// of memory used to store the object
return static_cast<char*>(addr); // treat that memory as bytes
}
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
inline void keep_window_open(string s)
{
if (s=="") return;
cin.clear();
cin.ignore(120,'\n');
for (;;) {
cout << "Please enter " << s << " to exit\n";
string ss;
while (cin >> ss && ss!=s)
cout << "Please enter " << s << " to exit\n";
return;
}
}
// error function to be used (only) until error() is introduced in Chapter 5:
inline void simple_error(string s) // write ``error: s and exit program
{
cerr << "error: " << s << '\n';
keep_window_open(); // for some Windows environments
exit(1);
}
// make std::min() and std::max() accessible on systems with antisocial macros:
#undef min
#undef max
// run-time checked narrowing cast (type conversion). See ???.
template<class R, class A> R narrow_cast(const A& a)
{
R r = R(a);
if (A(r)!=a) error(string("info loss"));
return r;
}
// random number generators. See 24.7.
inline int randint(int min, int max) { static default_random_engine ran; return uniform_int_distribution<>{min, max}(ran); }
inline int randint(int max) { return randint(0, max); }
//inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x
// container algorithms. See 21.9.
template<typename C>
using Value_type = typename C::value_type;
template<typename C>
using Iterator = typename C::iterator;
template<typename C>
// requires Container<C>()
void sort(C& c)
{
std::sort(c.begin(), c.end());
}
template<typename C, typename Pred>
// requires Container<C>() && Binary_Predicate<Value_type<C>>()
void sort(C& c, Pred p)
{
std::sort(c.begin(), c.end(), p);
}
template<typename C, typename Val>
// requires Container<C>() && Equality_comparable<C,Val>()
Iterator<C> find(C& c, Val v)
{
return std::find(c.begin(), c.end(), v);
}
template<typename C, typename Pred>
// requires Container<C>() && Predicate<Pred,Value_type<C>>()
Iterator<C> find_if(C& c, Pred p)
{
return std::find_if(c.begin(), c.end(), p);
}
#endif //H112
Error C2440 Build 'return': cannot convert from 'std::ifstream' to 'bool' Win32Project1 C:\Users\Leonardo\Documents\Visual Studio 2015\Projects\Win32Project1\Win32Project1\Graph.cpp 371
I suspect you're running into a breaking change introduced by C++11. The code appears to be this:
bool can_open(const string& s)
// check if a file named s exists and can be opened for reading
{
ifstream ff(s.c_str());
return ff;
}
The code used to work by using operator void * to cast ff from an istream to a void * which could then be cast to a bool. If the ifstream was bad the cast to void * would result in a null pointer which in turn would be treated as bool false.
But C++11 introduces an explicit operator bool() for streams (and gets rid of the void * operator?). Since the bool operator is explicit the operator won't be used for an implicit cast.
To get can_open to compile with the C++11 version of streams you need to make the cast explicit:
bool can_open(const string& s)
// check if a file named s exists and can be opened for reading
{
ifstream ff(s.c_str());
return (bool)ff;
}
However that change will break the code if it is compiled with a pre-C++11 version of streams.
I'm working on compiling the code for Acellerated c++ chapter 15. I more or less copied the code straight out of the book, except in some places they defined things like constructors in the class body in the header file, and I separated them out to avoid link errors.
Below is the code; I attempted to compile it in Visual Studio 2010, but unfortunately it fails. It tells me it cannot create instances of the "String_Pic" and the other derived classes (Frame_Pic, HCat_Pic, and VCat_Pic) because it says they are still abstract classes. It says the culprit is the "display" function, which it says is undefined. However, I clearly define it for each derived class, as you can see below.
What's going on here?
Header:
#ifndef _GUARD_PIC_BASE_H
#define _GUARD_PIC_BASE_H
#include "Ptr.h"
#include <iostream>
#include <string>
#include <vector>
class Picture;
class Pic_base {
friend std::ostream& operator<<(std::ostream&, const Picture&);
friend class Frame_Pic;
friend class HCat_Pic;
friend class VCat_Pic;
friend class String_Pic;
typedef std::vector<std::string>::size_type ht_sz;
typedef std::string::size_type wd_sz;
virtual wd_sz width() const = 0;
virtual ht_sz height() const = 0;
virtual void display(std::ostream, ht_sz, bool) const = 0;
public:
virtual ~Pic_base(){ }
protected:
static void pad(std::ostream&, wd_sz, wd_sz);
};
// public interface class and operations
class Picture {
friend std::ostream& operator<<(std::ostream&, const Picture&);
friend Picture frame(const Picture&);
friend Picture hcat(const Picture&, const Picture&);
friend Picture vcat(const Picture&, const Picture&);
public:
Picture(const std::vector<std::string>& =
std::vector<std::string>());
private:
Picture(Pic_base* ptr); //here's one difference
Ptr<Pic_base> p;
};
Picture frame(const Picture&);
Picture hcat(const Picture&, const Picture&);
Picture vcat(const Picture&, const Picture&);
std::ostream& operator<<(std::ostream&, const Picture&);
class String_Pic: public Pic_base {
friend class Picture;
std::vector<std::string> data;
String_Pic(const std::vector<std::string>&);
wd_sz width() const;
ht_sz height() const;
void display(std::ostream&, ht_sz, bool) const;
};
class VCat_Pic: public Pic_base {
friend Picture vcat(const Picture&, const Picture&);
Ptr<Pic_base> top, bottom;
VCat_Pic(const Ptr<Pic_base>&, const Ptr<Pic_base>&);
wd_sz width() const;
ht_sz height() const;
void display(std::ostream&, ht_sz, bool) const;
};
class HCat_Pic: public Pic_base {
friend Picture hcat(const Picture&, const Picture&);
Ptr<Pic_base> left, right;
HCat_Pic(const Ptr<Pic_base>&, const Ptr<Pic_base>&);
wd_sz width() const;
ht_sz height() const;
void display(std::ostream&, ht_sz, bool) const;
};
class Frame_Pic: public Pic_base {
friend Picture frame(const Picture&);
Ptr<Pic_base> p;
Frame_Pic(const Ptr<Pic_base>& pic);
wd_sz width() const;
ht_sz height() const;
void display(std::ostream&, ht_sz, bool) const;
};
#endif
.cpp/implementation file:
#include "Ptr.h"
#include "Pic_Base.h"
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
//Picture-Specific Functions:
Picture::Picture(Pic_base* ptr):p(ptr) {}
Picture::Picture(const vector<string>& v): p(new String_Pic(v)) { }
//Frame-Specific Functions:
Frame_Pic::Frame_Pic(const Ptr<Pic_base>& pic): p(pic) {}
Pic_base::wd_sz Frame_Pic::width() const { return p->width() + 4; }
Pic_base::ht_sz Frame_Pic::height() const { return p->height() + 4; }
void Frame_Pic::display(ostream& os, ht_sz row, bool do_pad) const{
if (row >= height()) {
// out of range
if (do_pad)
pad(os, 0, width());
} else {
if (row == 0 || row == height() - 1) {
// top or bottom row
os << string(width(), '*');
} else if (row == 1 || row == height() - 2) {
// second from fop or bottom row
os << "*";
pad(os, 1, width() - 1);
os << "*";
} else {
// interior row
os << "* ";
p->display(os, row - 2, true);
os << " *";
}
}
}
Picture frame(const Picture& pic){
return new Frame_Pic(pic.p);
}
//HCat-Specific Functions:
HCat_Pic::HCat_Pic(const Ptr<Pic_base>& l, const Ptr<Pic_base>& r): left(l), right(r) { }
HCat_Pic::HCat_Pic(const Ptr<Pic_base>& l, const Ptr<Pic_base>&r):
left(l), right(r) { }
Pic_base::wd_sz width() const { return left->width() + right->width(); }
Pic_base::ht_sz height() const { return max(left->height(), right->heigth()); }
void HCat_Pic::display(ostream& os, ht_sz row, bool do_pad) const{
left->display(os, row, do_pad || row < right->height());
right->display(os, row, do_pad);
}
Picture hcat(const Picture& l, const Picture& r){
return new HCat_Pic(l.p, r.p);
}
//VCat-Specific Functions:
VCat_Pic::VCat_Pic(const Ptr<Pic_base>& t, const Ptr<Pic_base>& b): top(t), bottom(b) { }
Picture vcat(const Picture& t, const Picture& b){
return new VCat_Pic(t.p, b.p);
}
Pic_base::wd_sz VCat_Pic::width() const {
return max(top->width(), bottom->width());
}
Pic_base::ht_sz VCat_Pic::height() const{
return top->height() + bottom->height();
}
void VCat_Pic::display(ostream& os, ht_sz row, bool do_pad) const{
wd_sz w = 0;
if (row < top->height()) {
// we are in the top subpicture
top->display(os, row, do_pad);
w = top->width();
} else if (row < height()) {
// we are in the bottom subpicture
bottom->display(os, row - top->height(), do_pad);
w = bottom->width();
}
if (do_pad)
pad(os, w, width());
}
//String_Pic-Specific Functions:
String_Pic::String_Pic(const std::vector<std::string>& v): data(v) { }
Pic_base::ht_sz String_Pic::height() const { return data.size(); }
Pic_base::wd_sz String_Pic::width() const{
Pic_base::wd_sz n = 0;
for (Pic_base::ht_sz i = 0; i != data.size(); ++i)
n = max(n, data[i].size());
return n;
}
void String_Pic::display(ostream& os, ht_sz row, bool do_pad) const{
wd_sz start = 0;
// write the row if we're still in range
if (row < height()) {
os << data[row];
start = data[row].size();
}
// pad the output if necessary
if (do_pad)
pad(os, start, width());
}
//Pic_base-Specific functions:
void Pic_base::pad(std::ostream& os, wd_sz beg, wd_sz end) {
while (beg != end) {
os << " ";
++beg;
}
}
//Non-Specific Functions:
ostream& operator<<(ostream& os, const Picture& picture){
const Pic_base::ht_sz ht = picture.p->height();
for (Pic_base::ht_sz i = 0; i != ht; ++i) {
picture.p->display(os, i, false);
os << endl;
}
return os;
}
You declare the pure virtual function as taking a ofstream object by value, while all your subclasses define it as taking a reference to one.
virtual void display(std::ostream, ht_sz, bool) const = 0;
vs
void display(std::ostream&, ht_sz, bool) const;
^
Pi_base declares display with this signature:
virtual void display(std::ostream, ht_sz, bool) const = 0;
But your derived classes declare it with this signature:
void display(std::ostream&, ht_sz, bool) const;
Compare them closely and you'll see that your base class takes a std::ostream while your derived classes take a std::ostream&.