creating arrays of objects that store arrays attributes - c++

Shape.h
class Shape {
private:
string name;
public:
Shape(name);
string getName();
void setName(string);
};
Triangle.h
class Triangle: public Shape {
private:
int x;
int y;
public:
Triangle(name,int[3],int[3]);
int getX();
int getY();
void setX(int);
void setY(int);
};
Triangle.cpp
Triangle::Triangle(string name,int _x[],int_y[]):Shape(name) {
x[] = _x[];
y[] = _y[];
}
int Square::getX() {
return x
}
int Square::getY() {
return y;
}
void Square::setX(int _x) {
x = _x;
}
void Square::setY(int _y) {
y = _y;
}
i need to create triangle that takes in name and 3 points of (x,y). when i try to create an array of triangle on the main Triangle Tri[50]; i got the following errors
Triangle::Triangle(std::string,int*,int*)
candidates expects 3 arguments, 0 provided
Triangle::Triangle(const Triangle&)
candidates expects 1 argument, 0 provided
can pls help me check what is wrong with my constructor?? is it because i am creating an array of objects that store arrays of x and y? so i need to use references and pointers for it?

When you create
Triangle Tri[50];
it will try to call the default constructor to initialize those elements in your Tri array, however, you did not provide such a default constructor and you did not call the constructor with 3 parameters, therefore, compiler complains.
Meanwhile, you seems to try to directly initialize one array with another inside the constructor of Triangle:
Triangle::Triangle(string name,int _x[],int_y[]):Shape(name) {
x[] = _x[];//^^I don't understand how this will work in practice.
y[] = _y[];
}
There is no direct assignment on arrays in C++, though C++ std::array (since C++11) has overloaded operator=, but this is not true for regular array.

Related

Error the default constructor of "Card" cannot be referenced -- it is a deleted function [duplicate]

So i created the class Point and want to use it as the parameter of the constructor in the class Circle , but the error : There is no default constructor for class "Point" shows up and I dont know how to fix it. The code is represented below this text:
class Point {
private:
int x, y;
public:
Point(int X, int Y) {
x = X;
y = Y;
}
};
class Circle {
private:
int radius;
Point centre;
public:
Circle(Point q, int r) {
centre = q;
radius = r;
}
};
int main() {
Point obj = Point(3, 4);
Circle obj = Circle(obj, 3);
}
The first problem is that when the constructor Circle::Cirlce(Point, int) is implicitly called by the compiler, before executing the body of that ctor, the data members centre and radius are default initialized. But since you've provided a user-defined ctor Point::Point(int, int) for class Point, the compiler will not synthesize the default ctor Point::Point(). Thus, the data member centre cannot be default initialized.
To solve this you can use constructor initializer list as shown below. The constructor initializer list shown below, copy initialize the data member centre instead of default initializing it.
class Point {
private:
int x, y;
public:
Point(int X, int Y) {
x = X;
y = Y;
}
};
class Circle {
private:
int radius;
Point centre;
public:
//--------------------------vvvvvvvvvvvvvvvvvvvv--->constructor initializer list used here
Circle(Point q, int r): radius(r), centre(q)
{
}
};
int main() {
Point obj = Point(3, 4);
Circle circleObj(obj,4);
}
Demo
Additionally, you had 2 objects with the same name obj inside main.

Segmentation fault when using vectors in the class and constructor

I was doing a list of programming projects, and this project is to make a 15 puzzle (slide puzzle). I was working on the project when I hit a small roadblock.
My code compiles just fine, but when I run it, I get a segmentation fault at line 12: pos[0] = x;
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Tile{
private:
vector<int> pos;
int value;
public:
Tile(int x, int y, int value_){
pos[0] = x;
pos[1] = y;
value = value_;
}
~Tile(){}
int getPos(int a){return pos[a];}
void setPos(int a, int b){pos[a] = b;}
};
int main(){
Tile tile1(1, 2, 10);
Tile* t1;
t1 = &tile1;
// returns position "x"
cout << t1->getPos(0);
return 0;
}
I mean, I could just do the whole project without having to use vectors/arrays to handle the position, but I do still want to know, for my own understanding in the future, why this doesn't work.
Based on the debug that I ran, the program is having trouble initializing the value of the pos[] vector.
Another issue: probably related, I tried setting the size of the vector when it was instantiated.
vector<int> pos(2);
But then I get the debug error:
error: expected identifier before numeric constant
Not sure whats going on here. I've tried a bunch of different things but I can't seem to figure out why my vectors don't work inside of classes.
I'm sure there are a hundred ways I could have done this little piece better, and I would love to know how you would have fixed it, but I also need to know what is wrong, specifically in the context of what I have written and tried.
Thanks.
I tried setting the size of the vector when it was instantiated.
vector<int> pos(2);
But then I get the debug error:
error: expected identifier before numeric constant
That's a compilation error, not a debug error.
You can't initialise members like that. However, you can (and should) initialise them using the parent constructor:
Tile(int x, int y, int value_)
: pos(2)
{
pos[0] = x;
pos[1] = y;
value = value_;
}
Currently you're just leaving your vector empty then accessing (and writing to!) elements that don't exist.
You really don't want a vector for this, anyway: that's a lot of dynamic allocation. How about a nice array? Or just two ints.
As mentioned in other answers, your vector is empty and your code is attempting to assign non-existent elements.
The solution is to always use initialisers instead of assignment. Rewrite your constructor as follows:
Tile(int x, int y, int value) :
pos{x, y},
value{value} {}
Note that the constructor body is now empty. All initialisation happens where it should — in the initialiser list.
Apart from that, your class does not need an explicitly defined destructor; the default destructor works just fine.
There are other issues with this class — for instance, what happens when the user does tile.setPos(3, 4)? A rule of thumb of good API design is to make it impossible to misuse the API.
Here’s how I would write your Tile class instead:
struct Tile {
int x;
int y;
int value;
Tile(int x, int y, int value) : x{x}, y{y}, value{value} {}
};
The getter and setter in your case wasn’t really doing any meaningful work. There’s an argument to be made to hide all data members behind accessors to future-proof access control. I’m no longer convinced this is actually useful but just in case, here’s a solution with that, too:
class Tile {
int x_;
int y_;
int value_;
public:
Tile(int x, int y, int value) : x_{x}, y_{y}, value_{value} {}
int x() const { return x; }
int& x() { return x; }
int y() const { return y; }
int& y() { return y; }
int value() const { return value; }
};
This makes x and y readable and writable (via assignment: t.x() = 42;), and value only readable. Other APIs are possible, with different sets of trade-offs. The important thing is to be consistent.
Your constructor doesn't set the size, so when you try to access/modify its contents, you are probably getting the exception.
Tile(int x, int y, int value_) : pos(2) {
pos[0] = x;
pos[1] = y;
value = value_;
}
You can use the initialization list of the constructor to call the vector's constructor, as in the code above.
There are couple of issue in the given code, which I have resolved and added comment in the code.
Issue in setPos and getPos might raise segmentation fault must be handle.
Added checks for the same.
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Tile{
private:
vector<int> pos;
int value;
public:
Tile(int x, int y, int value_){
pos.push_back(x); // this is equivalent to pos[0] = x, in this case
pos.push_back(y); // this is equivalent to pos[0] = y, in this case
value = value_;
}
~Tile(){}
int getPos(int a){
if(a >= pos.size()){
return -1; // if a is greater than size then pos[a] will raise the segmentation fault
}
return pos[a];
}
void setPos(int a, int b){
if(a >= pos.size()){
pos.resize(a+1); // to avoid segmentation fault, we are increasing the size if the given index is higher
// resize initialise the value with 0 as default value.
}
pos[a] = b;
}
};
int main(){
Tile tile1(1, 2, 10);
Tile* t1;
t1 = &tile1;
// returns position "x"
cout << t1->getPos(0);
return 0;
}

Difficulty getting barycentric_rational from c++ boost library to work how I need it to

I am using barycentric_rational from the C++ Boost library to interpolate on data stored in vectors. The vectors are populated inside a class, and I need the interpolation to be performed after the vectors have been populated, so I can write an access function to get the interpolated value at a specific point. Something like this:
class V{
public:
V(/* some arguments */){
//populate x and y
b=barycentric_rational<double>(x.data(),y.data(),x.size());
}
double psi(double r){
return b(r);
}
private:
std::vector<double> x,y;
barycentric_rational<double> b;
};
I get the error message:
error: no matching function for call to ‘boost::math::barycentric_rational<double>::barycentric_rational()
I think I get this message because b needs to be initialized in an initialiser list, but the code to populate x and y in my application is complicated. Setting x and y in a separate public method doesn't work for the same reason.
I have tried the following solution:
class V{
public:
V(/* some arguments */):b(nullptr){
//populate x and y
b=new barycentric_rational<double>(x.data(),y.data(),x.size());
}
~V(){
delete b;
}
double psi(double r){
return b->operator()(r);
}
private:
std::vector<double> x,y;
barycentric_rational<double> *b;
};
which seems to work. However, I don't like it for two reasons: a) I am using raw pointers, and eventually I need to be able to use copy and assignment operators which will get me into trouble, and b) I am sure there must be a neater way of doing this.
Please can someone suggest a way of doing what I need?
You can just init it in initialization list. If you need to use some special logic to populate x and y, you can do it in separate method.
class V{
public:
V(/* some arguments */)
: x(populateX()), y(populateY()), b(x.data(),y.data(),x.size())
{
}
std::vector<double> populateX() {
}
std::vector<double> populateY() {
}
double psi(double r){
return b(r);
}
private:
std::vector<double> x,y;
barycentric_rational<double> b;
};
If the code that populates x and y is too complecated, and initialization of x and y can not be done separately then you can move it to separate class:
struct XY {
XY(/* some args */) {
//init x and y
}
std::vector<double> x;
std::vector<double> y;
};
class V{
public:
V(/* some arguments */)
: xy(/*some args */), b(xy.x.data(),xy.y.data(),xy.x.size())
{
}
double psi(double r){
return b(r);
}
private:
XY xy;
barycentric_rational<double> b;
};
Another solution is just to initialize b with empty x and y, and then assign to it another correct value:
V(/* some arguments */) : b(x.data(),y.data(),x.size()){
//populate x and y
b=barycentric_rational<double>(x.data(),y.data(),x.size());
}

Store cursor position in class object (ncurses c++)

I am using QTCreator to compile my c++ code and the <curses.h> library.
Let us say we have the following class definition (.h):
struct coordinateYX
{
int y;
int x;
coordinateYX(long int yPos, long int xPos);
coordinateYX() {}
}
class Rogue
{
private:
long int health;
coordinateYX heroPosition;
public:
long int getHealth();
void setHealth(long int initHealth);
void healthChange(long int vDelta);
coordinateYX getHeroPosition();
void setHeroPosition(coordinateYX hPos);
};
and (.cpp):
coordinateYX::coordinateYX(long int yPos, long int xPos) : y{yPos}, x{xPos} {}
long int Rogue::getHealth() {return health;}
void Rogue::setHealth(long int initHealth) {health = initHealth;}
void Rogue::healthChange(long int vDelta) {health += vDelta;}
coordinateYX Rogue::getHeroPosition() {return heroPosition;}
void Rogue::setHeroPosition(coordinateYX hPos)
{
heroPosition.y = hPos.y;
heroPosition.x = hPos.x;
}
In my main.cpp, I am trying to store the current cursor position into an instantiation of Rogue:
Rogue Hero;
getyx(stdscr, Hero.getHeroPosition().y, Hero.getHeroPosition().x);
But I always get an error:
using temporary as lvalue [-fpermissive]
It also shows this below as part of the error which is in the <curses.h> file
#define getyx(w, y, x) (y = getcury(w), x = getcurx(w))
Although I can simply store these values in another struct initialized in main.cpp, how can I store the x and y positions directly in the class data members?
Thank you.
The quickest solution would be to change getHeroPosition to return a reference instead of value:
coordinateYX& Rogue::getHeroPosition() {return heroPosition;}
The problem is here you are trying to assign to the Rogue position:
getyx(stdscr, Hero.getHeroPosition().y, Hero.getHeroPosition().x);
This is equivalent to:
Hero.getHeroPosition().y = getcury(stdscr);
Hero.getHeroPosition().x = getcurx(stdscr);
But getHeroPosition returns the position by value (it returns a copy, an rvalue). If you assign a value to that temporary copy it will just be lost. The solution is to assign to a reference to the actual Rogue position (an lvalue).
Alternatively, you can use your existing setPosition function:
coordinateYX position;
getyx(stdscr, position.X, position.Y);
Hero.setPosition(position);

Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript - C++

I've this error when I try to save a number into my vector...
Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript
The code is:
class Elemento{
private:
int Nodo;
public:
Elemento(){};
~Elemento(){};
void SetNumero(int x) { Nodo = x; };
int GetNumero() { return Nodo; };
};
class MagicSquare{
private:
int N;
int Possibili_N;
int Magic_Constant;
vector<Elemento> Square(int Possibili_N);
public:
MagicSquare() { };
~MagicSquare() { };
void Set_N(int x) { N = x; };
void Set_PossibiliN(int x) { Possibili_N = x; };
void Set_MagicConstant(int x) { Magic_Constant = x; };
. . .
void SetSquare(int i, int x) { Square[i].SetNumero(x); }; // got error here
int GetSquare(int i) { return Square[i].GetNumero(); }; // got error here
};
I've got error whenever I use Square[i].method()...
I call a method that pass the index in the Square and the value to put in Elemento->Nodo, but I've to use a public method to access to private Nodo. The same with the GET. I want to get the value for displaying it.
You seem to have declared Square as a function, not a variable.
Instead, declare vector<Elemento> Square; and initialize it in the constructor.
You declared Square as a function, not a variable. So Square[i] is not valid.
Change
vector<Elemento> Square(int Possibili_N);
to
vector<Elemento> Square;
or call it using
Square(i)
if it is actually a function.
If you change it to a variable, you need to be sure to initialize it properly, preferably in the constructor.
Your line vector<Elemento> Square(int Possibili_N); is know as C++ most vexing parse.
Instead of declaring a member variable, as intended, you are declaring a function taking an int and returning a vector.
Instead, setup the member vector (and all other member variables) in the constructor initialization list:
class MagicSquare{
private:
int N;
int Possibili_N;
int Magic_Constant;
vector<Elemento> Square;
public:
MagicSquare( int n, int p, int m ) :
N( n ),
Possibili_N( p ),
Magic_Constant( m ),
Square( p ) {
}
...