I am working on a class project and im getting these errors, if anyone could possibly help that would be great, im new to stack overflow so im sorry if i dont post things properly.
The error states :Shapes.cpp:35:51: error: default argument given for parameter 2 of 'bool Point::draw(Screen&, char)' [-fpermissive]
bool Point::draw(Screen& scr, char ch = Screen::FG){
#ifndef Shapes_h
#define Shapes_h
#include<bits/stdc++.h>
using namespace std;
class Screen{
friend class Shape;
private:
size_t _w, _h;
vector<vector<char> > _pix;
public:
static const char FG = '*', BG = '.';
Screen(size_t w, size_t h){
_pix.resize(_h, vector<char>(_w));
}
size_t get_w() const{ return _w;}
size_t get_h() const{ return _h;}
vector<vector<char> >& get_pix() { return _pix;}
void set_w(size_t w) { _w = w;}
void set_h(size_t h) { _h = h;}
void clear() { fill(BG); }
void fill(char c); // todo cpp file
string to_string() const;
friend std::ostream& operator<<(std::ostream& os, const Screen& scr) {
return os << scr.to_string();
};
friend class Tests; // Don't remove this line
};
// SHAPE ---------------
class Shape{
public:
virtual ~Shape() {}
virtual bool draw(Screen& scr, char ch = Screen::FG) = 0;
friend class Tests;
};
class Point : public Shape {
private:
size_t _x, _y;
public:
Point(size_t x, size_t y) : _x(x), _y(y) {}
virtual ~Point() {}
bool draw(Screen& scr, char ch = Screen::FG);
friend class Tests;
};
class Line: public Shape{
private:
size_t _x1, _y1, _x2, _y2;
static bool draw_by_x(Screen& scr, char ch, size_t x1, size_t y1, size_t x2, size_t y2){
if (x2>x1){
draw_by_x(scr, ch, x2, y2, x1, y1);
}
double dy = (double) ((double)y2-y1)/((double)x2-x1);
size_t x = x1;
size_t y = y1;
bool boo = true;
for (size_t i = x1; i <= x2; i++){
boo &= Point((size_t)x, (size_t) y).draw(scr, ch);
x++; y += dy;
}
return boo;
}
static bool draw_by_y(Screen& scr, char ch, size_t x1, size_t y1, size_t x2, size_t y2){
if (x2>x1){
draw_by_x(scr, ch, x2, y2, x1, y1);
}
double dx = (double) ((double)x2-x1)/((double)y2-y1);
size_t x = x1;
size_t y = y1;
bool boo = true;
for (size_t i = x1; i <= x2; i++){
boo &= Point((size_t)x, (size_t) y).draw(scr, ch);
x += dx; y += 1;
}
return boo;
}
public:
Line(size_t a, size_t b, size_t c, size_t d) : _x1(a), _y1(b), _x2(c), _y2(d) {}
virtual ~Line() {}
bool draw(Screen& scr, char ch = Screen::FG);
friend class Tests; // Don't remove
};
class Quadrilateral: public Shape {
private:
size_t _x1, _y1, _x2, _y2, _x3, _y3, _x4, _y4;
public:
Quadrilateral(size_t a, size_t b, size_t c, size_t d, size_t e, size_t f, size_t g, size_t h):
_x1(a), _y1(b), _x2(c), _y2(d), _x3(e), _y3(f), _x4(g), _y4(h) {}
virtual ~Quadrilateral() {}
bool draw(Screen& scr, char ch = Screen::FG);
friend class Tests; // Don't remove
};
class Upright_Rectangle : public Quadrilateral {
public:
Upright_Rectangle(size_t x1,size_t y1, size_t x2, size_t y2) :
Quadrilateral(x1,y1, x1,y2, x2,y2, x2,y1) {}
virtual ~Upright_Rectangle() {}
};
class Stick_Man : public Shape{
static const size_t DEFAULT_W = 20, DEFAULT_H = 40;
private:
size_t _x, _y, _w, _h;
vector < Shape* > _parts;
public:
Stick_Man(size_t x = 0, size_t y = 0, size_t w = DEFAULT_W, size_t h = DEFAULT_H){
}
virtual ~Stick_Man();
const std::vector<Shape *>& get_parts() const { return _parts; }
bool draw(Screen& scr, char ch = Screen::FG){
return"";
}
friend class Tests; // Don't remove
};
#endif /* Shapes_h */
HERE IS MY CPP:
#include "Shapes.h"
#include<bits/stdc++.h>
#define pb push_back
using namespace std;
void Screen::fill(char c){
for (size_t i = 0; i < _h; i++){
for (size_t j = 0; j < _w; j++){
_pix[i][j] = c;
}
}
return;
}
void Screen::clear(char c){
fill(c);
return;
}
string Screen::to_string()const{
string ans = "";
for (size_t i = _h-1; i >= 0; i--){
for (size_t j = 0; j < _w; j++){
ans += _pix[i][j];
}
ans += "\n";
}
return ans;
}
bool Point::draw(Screen& scr, char ch = Screen::FG){
if (_x < scr.get_h() && _y < scr.get_w()){
scr.get_pix()[_x][_y] = ch;
return true;
}
return false;
}
bool Line::draw(Screen& scr, char ch = Screen::FG){
if (abs(int(_x1-_x2)) > abs(int(_y1-_y2))) return draw_by_x(scr, ch, _x1, _y1, _x2, _y2);
return draw_by_y(scr, ch, _x1, _y1, _x2, _y2);
}
bool Quadrilateral::draw(Screen& scr, char ch = Screen::FG){
size_t x1, y1, x2, y2, x3, y3, x4, y4;
x1 = _x1;
x2 = _x2;
x3 = _x3;
x4 = _x4;
y1 = _y1;
y2 = _y2;
y3 = _y3;
y4 = _y4;
if ((x2-x3)==(x4-x1) && (y2-y3)==(y4-y1)){
swap(x2, x3);
swap(y2, y3);
}
else if ((x4-x3)==(x2-x1) && (y4-y3)==(y2-y1)){
swap(x4, x3);
swap(y4, y3);
}
bool boo = true;
boo &= Line(x1, y1, x2, y2).draw(scr, ch);
boo &= Line(x2, y2, x3, y3).draw(scr, ch);
boo &= Line(x3, y3, x4, y4).draw(scr, ch);
return boo;
}
Remove the default parameter from the definition. Instead of
bool Point::draw(Screen& scr, char ch = Screen::FG){
if (_x < scr.get_h() && _y < scr.get_w()){
scr.get_pix()[_x][_y] = ch;
return true;
}
Change it to
bool Point::draw(Screen& scr, char ch){
if (_x < scr.get_h() && _y < scr.get_w()){
scr.get_pix()[_x][_y] = ch;
return true;
}
The reason you get the error is because you've already declared and defined it the draw function within the class here
bool draw(Screen& scr, char ch = Screen::FG){
return"";
}
Change this to
bool draw(Screen& scr, char ch = Screen::FG){
}
And you won't get the redefinition error anymore.
Related
I tried to write a simple game and I accidently got errors
"No matching function for call to Monster::Monster()"
and
"No matching function for call to Player::Player()".
Both were for the Game class constructor. Class Game is not related to classes Monster or Player in any way. Here are the codes.
main.cpp
#include <game.h>
#include <iostream>
using namespace std;
int main() {
Game game = Game( );
while(!game.hasFinished( )) {
game.round( );
}
}
game.h
#ifndef GAME
#define GAME
#include <entity.h>
class Game {
private:
bool finished = false;
char area[15][15];
char defaultSign = '*';
int size = 15;
Monster monsters[4];
Player player;
int score = 0;
void cls();
void fill();
void display();
void playerMove();
public:
Game();
void round();
int getScore();
bool hasFinished();
};
#endif
game.cpp
#include <game.h>
#include <iostream>
#include <conio.h>
Game::Game() {
player = Player(7, 7);
monsters[0] = Monster(0, 0);
monsters[1] = Monster(size - 1, size - 1);
monsters[2] = Monster(size - 1, 0);
monsters[3] = Monster(0, size - 1);
}
bool Game::hasFinished() {
return !finished;
}
int Game::getScore() {
return score;
}
void Game::cls() {
for(int i = 0; i < 50; i++) {
std::cout << "\n";
}
}
void Game::fill() {
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
area[i][j] = defaultSign;
}
}
for(int i = 0; i < 4; i++) {
area[monsters[i].getX( )][monsters[i].getY( )] = monsters[i].getSign( );
}
area[player.getX( )][player.getY( )] = player.getSign( );
}
void Game::display() {
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
std::cout << area[i][j];
}
std::cout << "\n";
}
}
void Game::round() {
cls( );
fill( );
display( );
playerMove( );
for(int i = 0; i < 4; i++) {
monsters[i].moveTowards(player);
}
score++;
}
void Game::playerMove() {
bool moved = false;
while(!moved) {
char c = getch( );
if(c == 'w' || c == 'W') {
player.move(player.getX( ), player.getY( ) + 1);
moved = true;
}
if(c == 'a' || c == 'A') {
player.move(player.getX( ) - 1, player.getY( ));
moved = true;
}
if(c == 's' || c == 'S') {
player.move(player.getX( ), player.getY( ) - 1);
moved = true;
}
if(c == 'd' || c == 'D') {
player.move(player.getX( ) + 1, player.getY( ));
moved = true;
}
}
}
entity.h
#ifndef ENTITY
#define ENTITY
class Entity {
protected:
int x, y;
char sign;
public:
Entity(int xPos, int yPos);
int getX();
int getY();
void move(int xPos, int yPos);
char getSign();
};
class Player : public Entity {
private:
char sign = 'P';
public:
Player(int xPos, int yPos);
};
class Monster : public Entity {
private:
char sign = 'M';
public:
Monster(int xPos, int yPos);
void moveTowards(Entity p);
};
#endif
entity.cpp
#include <entity.h>
Entity::Entity(int xPos, int yPos) {
x = xPos;
y = yPos;
sign = '*';
}
void Entity::move(int xPos, int yPos) {
x = xPos;
y = yPos;
}
int Entity::getX() {
return x;
}
int Entity::getY() {
return y;
}
char Entity::getSign() {
return sign;
}
Player::Player(int xPos, int yPos)
: Entity(xPos, yPos) {
}
Monster::Monster(int xPos, int yPos)
: Entity(xPos, yPos) {
}
void Monster::moveTowards(Entity p) {
int moveArea[2] = {x, y};
if(x > p.getX( )) moveArea[0]--;
if(x < p.getX( )) moveArea[0]++;
if(y > p.getY( )) moveArea[1]--;
if(y < p.getY( )) moveArea[1]++;
move(moveArea[0], moveArea[1]);
}
Please, help!
The problem is
Monster monsters[4]; // ---> Means initiliaze 4 Monsters with a ctor which takes no arguments(eg default Ctor)
Player player; ---> //The initiliaze 1 Player with a ctor which take no arguments
Since you defined Monster(int xPos, int yPos); default Ctors are deleted. You have to define them yourself. Entity has the same problem. I compiled your code , if you do like below it will work.
Add "Entity() = default;" , initiliaze x and y like below,
class Entity {
protected:
int x = 0; --> Critical
int y = 0; --> Critical
char sign;
public:
Entity() = default; --> Critical
Entity(int xPos, int yPos);
int getX();
int getY();
void move(int xPos, int yPos);
char getSign();
};
Do the same for player and monster
class Monster : public Entity {
private:
char sign = 'M';
public:
Monster(int xPos, int yPos);
Monster() = default; --> Critical
void moveTowards(Entity p);
};
class Player : public Entity {
private:
char sign = 'P';
public:
Player() = default; --> Critical
Player(int xPos, int yPos);
};
You should add a default constructor to your Monster class because it's implicitly called when the Monster array is initialized. If you don't want to do that for some reason, you could change the Monster array contain raw or smart pointers to Monster objects.
I'm trying to construct a two-dimensional boolean array with a class I've created called Grid. The Grid object is a private member class of another class called GameOfLife. Whenever I create a GameOfLife object with the parameters belove, the Grid object first gets created with the default constructor, then it gets created again with the constructor with parameters, and then for some reason Grid's deconstructor runs and deletes everything ? I'm really out of ideas :p I'm running MinGW GCC on Eclipse Luna.
Main.cpp
const int HEIGHT = 25;
const int WIDTH = 25;
#include <iostream>
#include "GameOfLife.h"
int main(int argc, const char * argv[]) {
GameOfLife game = GameOfLife(HEIGHT, WIDTH, false);
game.play();
return 0;
}
Grid.h
#ifndef __Game_Of_Life__Grid__
#define __Game_Of_Life__Grid__
#include <stdio.h>
class Grid {
public:
Grid(int y, int x, bool state);
Grid();
void allocate(int x, int y, bool state);
void deallocate();
void set(int x, int y, bool state);
bool get(int x, int y);
void setAll(bool state);
void switchBoards();
~Grid();
private:
bool ** oldGeneration;
bool ** newGeneration;
int height;
int width;
};
#endif /* defined(__Game_Of_Life__Grid__) */
Grid.cpp
#include "Grid.h"
Grid::Grid(int y, int x, bool state) {
allocate(x, y, state);
}
void Grid::allocate(int x, int y, bool state) {
height = y;
width = x;
oldGeneration = new bool*[height];
newGeneration = new bool*[height];
for (int i = 0; i < height; i++) {
oldGeneration[i] = new bool[width];
newGeneration[i] = new bool[width];
}
}
Grid::~Grid() {
deallocate();
}
void Grid::switchBoards() {
bool ** temp = oldGeneration;
oldGeneration = newGeneration;
newGeneration = temp;
delete temp;
}
bool Grid::get(int x, int y) {
return oldGeneration[y][x];
}
void Grid::set(int x, int y, bool state) {
newGeneration[y][x] = state;
}
void Grid::deallocate() {
if (oldGeneration != NULL || newGeneration != NULL) {
for (int i = 0; i < height; i++) {
delete [] oldGeneration[i];
delete [] newGeneration[i];
}
delete [] oldGeneration;
delete [] newGeneration;
}
return;
}
Grid::Grid() {
oldGeneration = NULL;
newGeneration = NULL;
width = 0;
height = 0;
}
void Grid::setAll(bool state) {
for (int i = 0; i < height; i++) {
for (int n = 0; n < width; n++) {
newGeneration[i][n] = state;
}
}
}
GameOfLife.h
#ifndef __Game_Of_Life__GameOfLife__
#define __Game_Of_Life__GameOfLife__
#include <stdio.h>
#include "Grid.h"
#include <iostream>
class GameOfLife {
private:
Grid board;
public:
GameOfLife(int y, int x, bool state);
GameOfLife();
~GameOfLife();
void play();
void welcome();
void makeBoard();
void updateBoard();
int findAliveNeighbours(int x, int y);
};
#endif /* defined(__Conway__GameOfLife__) */
GameOfLife.cpp
#include "GameOfLife.h"
const int WIDTH = 100;
const int HEIGHT= 75;
GameOfLife::GameOfLife(int y, int x, bool state) {
board = Grid(y, x, state);
}
GameOfLife::GameOfLife() {
board = Grid();
}
GameOfLife::~GameOfLife() {
board.deallocate();
}
void GameOfLife::play() {
welcome();
makeBoard();
for (int i = 0; i < HEIGHT; i++) {
for (int n = 0; n < WIDTH; n++) {
std::cout << board.get(n,i) << " ";
}
std::cout << std::endl;
}
updateBoard();
std::cout << std::endl;
for (int i = 0; i < HEIGHT; i++) {
for (int n = 0; n < WIDTH; n++) {
std::cout << board.get(n,i) << " ";
}
std::cout << std::endl;
}
}
void GameOfLife::makeBoard() {
int x1,x2,x3,x4, y1,y2,y3,y4;
x1 = 10; y1 = 10;
x2 = 10; y2 = 11;
x3 = 10; y3 = 12;
x4 = 11; y4 = 13;
int x5 = 0; int y5 = 0;
board.set(x1, y1, true);
board.set(x2, y2, true);
board.set(x3, y3, true);
board.set(x4, y4, true);
board.set(x5, y5, true);
}
void GameOfLife::welcome() {
std::cout << "Welcome to Conway's Game Of Life"
<< std::endl;
}
GameOfLife::GameOfLife(int y, int x, bool state) {
// board is a member variable that gets initialized
// with the default constructor.
// Then it gets replaced by assignment with a different
// Grid object. The temporary object gets deleted at
// the end of the line.
board = Grid(y, x, state);
}
Change the implementation to:
GameOfLife::GameOfLife(int y, int x, bool state) : board(y, x, state) {}
Similarly, change the default constructor to:
GameOfLife::GameOfLife() {}
The more important problem that needs to be fixed is that you are breaking The Rule of Three.
You need to add proper implementations of the copy constructor and the copy assignment opertor in Grid.
The other, and better, option is to change the internal data of Grid to
std::vector<std::vector<bool>> oldGeneration;
std::vector<std::vector<bool>> newGeneration;
Then, the compiler generated copy constructor and copy assignment operator will be good enough.
Happy Sunday everyone!
I am trying to teach myself C++ so I am doing a Battleship program.
This version is fairly standard. The player enters the coordinates of a cell to try to hit a ship. The program stating if a ship is hit. If all cells occupied by a ship are hit, the program prints a message stating that that ship is sunk. After each attempt, the program prints the current state by showing the board with all successful attempts marked by "*" or "x"respectively.
What I am having trouble with is writing the level function in my Board class which sums up all the levels of the ships on the board.
So I have a board like this for the Battleships
a b c d e f g h i j
+-------------------+
0| |
1| |
2| |
3| |
4| |
5| |
6| |
7| |
8| |
9| |
+-------------------+
This is my board header file for context :
#ifndef BOARD_H
#define BOARD_H
#include "Ship.h"
#include <vector>
class Board
{
public:
Board(void);
void addShip(char type, int x1, int y1, int x2, int y2);
void print(void);
void hit(char c, int i);
int level(void);
private:
std::vector<Ship *> shipList;
char score[10][10];
Ship *shipAt(int x, int y);
};
#endif
I also have a ship class to store the coordinates of the ship
Here is my ship header (it may not be necessary to read everything just look at the level function):
//
// Ship.h
//
#ifndef SHIP_H
#define SHIP_H
class Ship
{
public:
virtual ~Ship(void) {}
virtual const char *name(void) const = 0;
virtual int size(void) const = 0;
int getX(int i) const;
int getY(int i) const;
void print(void) const;
bool includes(int x, int y);
int level(void) const;
void decreaseLevel(void);
static Ship *makeShip(char ch, int x1, int y1, int x2, int y2);
protected:
void setPos(int a1, int b1, int a2, int b2);
int lev;
private:
bool checkConfig(int x1, int y1, int x2, int y2);
int x1,y1,x2,y2;
};
class AircraftCarrier : public Ship
{
public:
AircraftCarrier(int x1, int y1, int x2, int y2);
virtual const char *name(void) const;
virtual int size(void) const;
};
class BattleShip: public Ship
{
public:
BattleShip(int x1, int y1, int x2, int y2);
virtual const char *name(void) const;
virtual int size(void) const;
};
class Cruiser: public Ship
{
public:
Cruiser(int x1, int y1, int x2, int y2);
virtual const char *name(void) const;
virtual int size(void) const;
};
class Destroyer: public Ship
{
public:
Destroyer(int x1, int y1, int x2, int y2);
virtual const char *name(void) const;
virtual int size(void) const;
};
#endif
Here is my ship class (it may not be necessary to read everything so I just put the level function)
#include "Ship.h"
#include <iostream>
#include <stdexcept>
using namespace std;
//LOTS OF CODE I OMITTED FOR BREVITY
int Ship::level (void) const
{
return lev;
}
}
In my ship class the
int level(void)
function returns the current value of the protected variable lev
Here is what I have so far for my Board.cpp (sorry for the long bits of code but it is necessary to provide context for this question):
#include "Board.h"
#include "Ship.h"
#include <iostream>
using namespace std;
#include <vector>
#include <string.h>
#include <stdexcept>
//member function definitions
Board::Board(void)
{
//char score[10][10] = " ";
char score[10][10] = {{' '}};
}
void Board::addShip(char type, int x1, int y1, int x2, int y2)
{
if(shipList.size()<=9)
{
shipList.push_back(Ship::makeShip(type ,x1 , y1, x2, y2)) ;
}
}
void Board::print(void){
cout<< " a b c d e f g h i j"<< endl;
cout <<" +-------------------+"<< endl;
for (int i = 0; i < 10; i++) {
cout<<" "<< i <<"|" ;
for (int j = 0; j < 10; j++) {
cout << score[i][j];
}
if(i == 0){
cout << " |";
}
else{
cout << " |";
}
cout<< endl;
}
cout <<" +-------------------+"<< endl;
}
void Board::hit(char c, int i){
if (c<'a' || c>'j' || i > 9 || i<0){
throw invalid_argument("invalid input");
}
Ship* ship = shipAt(i, c-'a');
if (ship) {
score[i][c-'a']= '*';
}
else{
score[i][c-'a']= 'x';
}
}
Ship* Board::shipAt(int x, int y){
Ship* ship = shipAt(x, y);
if (ship){
return ship; }
else{
return NULL;
}
}
int Board::level(void)
{
}
In int level(void)
The function should return the sum of the levels of all ships on the board.
Essentially I do not know how I would implement int level(void)in my board class I am trying to call each ship pointer's level and add to a sum by pointing the shipList pointer to level in each iteration of the loop. But I am struggling to execute that.
I suggest a range-based for loop (C++11) through ShipList to get each Ship pointer and accumulate the level:
int Board::level() {
int level = 0;
for(Ship* ship : shipList)
level += ship->level();
return level;
}
I think this looks cleaner than an iterator or index-based for loop, especially when the elements are pointers.
Iterate over the list of Ships and accumulate the levels of each Ship. Return the accumulated value.
int Board::level(void)
{
int lev = 0;
std::vector<Ship *>::iterator iter = shipList.begin();
std::vector<Ship *>::iterator end = shipList.end();
for ( ; iter != end; ++iter )
{
lev += (*iter)->level();
}
return lev;
}
I have 2 classes : 1 brick and 1 construction class, I must built a house or an object with bricks, each construction can take a brick as an argument, it has also operators + , - and ^ , and +=, -= , ^= , that add a construction on the right of the construction, "behind" (in the depth and 1 level above a construction...
I have to do this with the appropriate according indices of my 3 dimensional vector....
The problem is: Everything compiles fine, but my program crashes when I start this... I spent a whole day on this program and I dont know where my error is...
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Pour simplifier
typedef string Forme ;
typedef string Couleur ;
class Brique
{
private:
Forme forme ;
Couleur couleur ;
public:
/*****************************************************
Compléter le code à partir d'ici
*******************************************************/
Brique( Forme f, Couleur c ) : forme(f),couleur(c) {};
ostream& afficher(ostream& sortie) const ;
Forme getForme() const {return forme;};
Couleur getCouleur() const {return couleur;};
};
ostream& Brique::afficher(ostream & sortie) const {
if (this->getCouleur() != "") {
return sortie<<"("<<this->getForme()<<", "<<this->getCouleur()<<")";
}
else {
return sortie<<this->getForme();
}
};
ostream& operator<<(ostream& sortie, Brique const& z) {
return z.afficher(sortie);
};
class Construction
{
friend class Grader;
public:
vector<vector<vector<Brique> > > contenu;
public:
Construction(Brique b) : contenu(1, vector<vector<Brique> >(1, vector<Brique>(1,b))) {};
//Construction(Construction c) ;
ostream& afficher(ostream& sortie) const ;
Construction& operator^=(Construction const & z) ;
Construction& operator-=(Construction const & z) ;
Construction& operator+=(Construction const & z) ;
};
ostream& Construction::afficher(ostream& sortie) const {
size_t i(contenu.size());
for (size_t j = 0; j< i; j++) {
cout<<"Couche "<<j<<" :"<<endl;
for (size_t k = 0; k<contenu[j].size() ; k++) {
for (size_t t = 0; t< contenu[j][k].size(); t++) {
cout <<contenu[j][k][t];
}
}
}
return cout;
};
ostream& operator<<(ostream& o, Construction const& z) {
return z.afficher(o);
};
Construction& Construction::operator^=(Construction const & z) {
//int i(this->contenu.size());
//int j(this->contenu[i].size());
//int k(this->contenu[i][j].size());
int m(z.contenu.size());
//int n(z.contenu[m].size());
//int p(z.contenu[m][n].size());
this->contenu.push_back(z.contenu[m]);
return *this;
};
Construction& operator^(Construction & o, Construction & z) {
//o.contenu.push_back(z.contenu[z.contenu.size()]);
o^= z;
return o;
}
Construction& Construction::operator+=(Construction const & z) {
int i(this->contenu.size());
int j(this->contenu[i].size());
//int k(this->contenu[i][j].size());
int m(z.contenu.size());
int n(z.contenu[m].size());
//int p(z.contenu[m][n].size());
if ( n < j) { return *this;}
else if ( n > j) {
int a(0);
for (auto element : z.contenu[m][n]) {
this->contenu[i][j].push_back(element);
++a;
if (a == n) { return * this;}
}
}
else {
this->contenu[i].push_back(z.contenu[m][n]);
}
return *this;
}
Construction operator+(Construction t, Construction z) {
return t+=z;
}
Construction& Construction::operator-=(Construction const & z) {
int i(this->contenu.size());
int j(this->contenu[i].size());
int k(this->contenu[i][j].size());
int m(z.contenu.size());
int n(z.contenu[m].size());
int p(z.contenu[m][n].size());
if ( p < k) { return *this;}
else {
this->contenu[i][j].push_back(z.contenu[m][n][p]);
}
return *this;
}
Construction& operator-(Construction & o, Construction const & z) {
/*
int i(o.contenu.size());
int m(z.contenu.size());
int n(z.contenu[m].size());
int p(z.contenu[m][n].size());
o.contenu[i][m].push_back(z.contenu[m][n][p]);
*/
return o-=z;
}
const Construction operator*(unsigned int n, Construction const& a)
{
Construction b = a;
for (unsigned int i=1;i<n;i++) {
b.operator+=(a);
}
return b;
};
const Construction operator/(unsigned int n, Construction const& a)
{
Construction b=a;
for (unsigned int i=1;i<n;i++) {
b^=a;
}
return b;
};
const Construction operator%(unsigned int n, Construction const& a)
{
Construction b=a;
for (unsigned int i=1;i<n;i++) {
b-=a;
}
return b;
};
/*******************************************
* Ne rien modifier après cette ligne.
*******************************************/
int main()
{
// Modèles de briques
Brique toitD("obliqueD", "rouge");
Brique toitG("obliqueG", "rouge");
Brique toitM(" pleine ", "rouge");
Brique mur (" pleine ", "blanc");
Brique vide (" ", "");
unsigned int largeur(4);
unsigned int profondeur(3);
unsigned int hauteur(3); // sans le toit
// on construit les murs
Construction maison( hauteur / ( profondeur % (largeur * mur) ) );
cout<<maison;
// on construit le toit
Construction toit(profondeur % ( toitG + 2*toitM + toitD ));
toit ^= profondeur % (vide + toitG + toitD);
// on pose le toit sur les murs
maison ^= toit;
// on admire notre construction
cout << maison << endl;
return 0;
}
anybody got an Idea why my program crashes?
This is my program:
#include <iostream>
using namespace std;
class Point
{
private: int x, y;
public:
Point(int f = 0, int g = 0)
{
x = f;
y = g;
}
int getX() const
{
return x;
}
int getY() const
{
return y;
}
void setX(const int new_x)
{
x = new_x;
}
void setY(const int new_y)
{
y = new_y;
}
};
class PointArray
{
private:
Point * loc;
int len;
public:
PointArray()
{
len = 0;
loc = new Point[0];
}
PointArray(const Point * points, const int size)
{
len = size;
loc = new Point[len];
for(int f = 0; f < len; f++)
loc[f] = points[f];
}
PointArray(const PointArray& pv)
{
len = pv.len;
loc = new Point[len];
for(int f = 0; f < len; f++)
loc[f] = pv.loc[f];
}
~PointArray()
{
delete[] loc;
}
void resize(int n)
{
Point *loc1 = new Point[n];
for(int f = 0; f < len && f < n; f++)
loc1[f] = loc[f];
len = n;
delete[] loc;
loc = loc1;
}
void pushBack(const Point &p)
{
resize(len+1);
loc[len-1] = p;
}
void insert(const int pos, const Point &p)
{
resize(len+1);
for(int f = len-1; f > pos; f--)
loc[f] = loc[f-1];
loc[pos] = p;
}
void remove(const int pos)
{
for(int f = pos; f < len-1; f++)
loc[f] = loc[f+1];
resize(len-1);
}
const int getSize() const
{
return len;
}
void clear()
{
resize(0);
}
Point * get(const int pos)
{
if (pos >= len)
return NULL;
else
{
Point * x = new Point();
*x = loc[pos];
return x;
}
}
const Point * get(const int pos) const
{
if (pos >= len)
return NULL;
else
{
Point * x = new Point();
*x = loc[pos];
return x;
}
}
};
class Polygon
{
protected:
PointArray * loci;
int sides;
static int N;
public:
Polygon(Point * loc, int len)
{
loci = new PointArray(loc, len);
sides = len;
N++;
}
Polygon(const PointArray& pv)
{
loci = new PointArray(pv);
sides = pv.getSize();
N++;
}
Polygon(const Polygon& pv)
{
loci = new PointArray(*pv.loci);
sides = pv.sides;
N++;
}
~Polygon()
{
delete loci;
N--;
}
virtual double area() = 0;
static int getNumPolygons()
{
return N;
}
int getNumSides()
{
return sides;
}
const PointArray * getPoints()
{
return loci;
}
};
class Rectangle : public Polygon
{
private:
typedef Polygon super;
void makeRectangle(const Point e, const Point r)
{
Point * loci = new Point[4];
loci[0] = e;
loci[2] = r;
loci[1] = new Point(e.getX(), r.getY());
loci[3] = new Point(r.getX(), e.getY());
}
void makeRectangle (const int x1, const int x2, const int y1, const int y2)
{
Point * loci = new Point[4];
loci[0] = new Point(x1, y1);
loci[1] = new Point(x2, y1);
loci[2] = new Point(x2, y2);
loci[3] = new Point(x1, y2);
}
};
The compiler is giving me these errors in the two overloaded makeRectangle() when they call the Point(int, int) constructor, saying:
geometry.cpp: In member function 'void Rectangle::makeRectangle(Point, Point)':
geometry.cpp:170:45: error: invalid conversion from 'Point*' to 'int' [-fpermissive]
geometry.cpp:8:4: error: initializing argument 1 of 'Point::Point(int, int)' [-fpermissive]
geometry.cpp:171:45: error: invalid conversion from 'Point*' to 'int' [-fpermissive]
geometry.cpp:8:4: error: initializing argument 1 of 'Point::Point(int, int)' [-fpermissive]
geometry.cpp: In member function 'void Rectangle::makeRectangle(int, int, int, int)':
geometry.cpp:176:33: error: invalid conversion from 'Point*' to 'int' [-fpermissive]
geometry.cpp:8:4: error: initializing argument 1 of 'Point::Point(int, int)' [-fpermissive]
geometry.cpp:177:33: error: invalid conversion from 'Point*' to 'int' [-fpermissive]
geometry.cpp:8:4: error: initializing argument 1 of 'Point::Point(int, int)' [-fpermissive]
geometry.cpp:178:33: error: invalid conversion from 'Point*' to 'int' [-fpermissive]
geometry.cpp:8:4: error: initializing argument 1 of 'Point::Point(int, int)' [-fpermissive]
geometry.cpp:179:33: error: invalid conversion from 'Point*' to 'int' [-fpermissive]
geometry.cpp:8:4: error: initializing argument 1 of 'Point::Point(int, int)' [-fpermissive]
Because x1, x2, y1, and y2 are integers and therefore should be compatible with the Point(int, int) constructor, I do not understand why it is giving me the error: "invalid conversion from 'Point*' to 'int'".
Getters and setters
Having getters and setters for the sake of having them is never a good idea. Therefore your code for Point can be reduced to:
struct Point {
int x;
int y;
};
Which not only is easier and faster to read, but is just as constant correct as your solution was.
The array
Your PointArray class is less than reusable. You can use standard containers instead. Your PointArray class can be reduced to:
using PointArray = std::vector<Point>;
The Polygon base class
The Polygon class can also be improved. First of all you don't need loci to be dynamically allocated. You should use:
class Polygon {
protected:
PointArray loci;
int sides;
static int N;
Now, for the constructor you could use the following instead of the C-style array that you are expecting from the first constructor:
public:
Polygon(const PointArray& loc) {
loci = loc
sides = loc.size();
N++;
}
As you can see there's no need for the len argument. You could also use an std::initializer_list to allow expressions like:
Polygon x { Point(...), Point(...), Point(...), ... };
And here's how:
Polygon(const std::initializer_list<Point> list)
: loci(list)
, sides(list.size())
{ N++; }
And after your smart edit you can get rid of the custom copy constructor and destructor, effectively following the Rule of Zero.
The rest is pretty much the same:
virtual double area() = 0;
static int getNumPolygons() { return N; }
int getNumSides() { return sides; }
except for getPoints. I'd suggest two different overloads: const and non-const:
PointArray& getPoints() { return loci; }
const PointArray& getPoints() const { return loci; }
};
The Rectangle class
And finally your rectangle class can, of course, be improved:
class Rectangle : public Polygon {
private:
void makeRectangle(const Point& e, const Point& r) {
loci.push_back(e);
loci.push_back(r);
loci.emplace_back(e.x, r.y);
loci.emplace_back(r.x, e.y);
}
void makeRectangle (const int x1, const int x2, const int y1, const int y2) {
loci.emplace_back(x1, y1);
loci.emplace_back(x2, y1);
loci.emplace_back(x2, y2);
loci.emplace_back(x1, y2);
}
};
Conclusion
After this simple refactoring, all your errors should be gone and your code should be much shorter and readable.