C++ - Structure Methods Syntax - c++

I get a weird error when I try and compile the following code:
I need to use structs (I was taught classes with the struct keywor, and am trying to learn it that way. I also need to put the function definitions outside the struct block.
#include <iostream>
#include <string>
using namespace std;
struct Box {
int l;
int w;
int area();
Box();
Box(int a, int b);
Box operator+(const Box a, const Box b);
};
Box::Box() {
l = 0;
w = 0;
}
Box::Box(int a, int b) {
l = a;
w = b;
}
Box Box::operator+(const Box a, const Box b) {
Box box(a.l + b.l, a.w + b.w);
return box;
}
int Box::area() {
return l * w;
}
int main() {
Box a(1, 2);
Box b;
b.l = 3;
b.w = 4;
Box c = a + b;
cout << "Total area is: " << a.area() << " + " << (b.area) << " = " << (c.area) << endl;
}
Could someone help me out? Thanks

operator+ which belongs to the class/struct should receive only one parameter of type Box (from the right side of +) which should be added to the current object (from the left side of +):
Box Box::operator+(const Box& a) {
Box box(a.l + l, a.w + w);
return box;
}
Also in the cout line it should be b.area() and c.area() instead of (b.area) and (c.area).

Here's your code modified a bit. I had to put the operator overload into the struct due to the compiler not using NRVO (See here)
#include <iostream>
#include <string>
using namespace std;
struct Box {
int l;
int w;
Box();
Box(int a, int b);
int area();
Box operator+(const Box a)
{
return Box(a.l + l, a.w + w);
}
};
Box::Box() {
l = 0;
w = 0;
}
Box::Box(int a, int b) {
l = a;
w = b;
}
int Box::area() {
return l * w;
}
int main() {
Box a(1, 2);
Box b;
b.l = 3;
b.w = 4;
Box c = a + b;
cout << "Total area is: " << a.area() << " + " << (b.area()) << " = " << (c.area()) << endl;
}
Result:
Total area is: 2 + 12 = 24

Related

expression preceeding of apparent call must have pointer-to func type

I have a class that I'm trying to use, but in main function ёstartё doesn't execute with following error expression preceeding of apparent call must have pointer-to func type
#include <queue>
#include <limits>
#include <cmath>
#include <iostream>
// represents a single pixel
class Node {
public:
int idx; // index in the flattened grid
float cost; // cost of traversing this pixel
Node(int i, float c) : idx(i), cost(c) {}
};
bool operator<(const Node &n1, const Node &n2) {
return n1.cost > n2.cost;
}
bool operator==(const Node &n1, const Node &n2) {
return n1.idx == n2.idx;
}
// various grid heuristics:
// http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S7
float linf_norm(int i0, int j0, int i1, int j1) {
return std::max(std::abs(i0 - i1), std::abs(j0 - j1));
}
// manhattan distance
float l1_norm(int i0, int j0, int i1, int j1) {
return std::abs(i0 - i1) + std::abs(j0 - j1);
}
// weights: flattened h x w grid of costs
// h, w: height and width of grid
// start, goal: index of start/goal in flattened grid
// diag_ok: if true, allows diagonal moves (8-conn.)
// paths (output): for each node, stores previous node in path
class Astar {
public:
float* weights = nullptr;
int h;
int w;
int start;
int goal;
bool diag_ok;
int* paths = nullptr;
void setVariables(float* weightsInput, int hInput, int wInput, int startInput, int goalInput, bool diag_okInput, int* pathsInput) {
weights = weightsInput;
h = hInput;
w = wInput;
start = startInput;
goal = goalInput;
diag_ok = diag_okInput;
paths = pathsInput;
}
void start() {
const float INF = std::numeric_limits<float>::infinity();
std::cout << "width : " << w << " " << "height : " << h << std::endl;
std::cout << "start : " << start << " goal : " << goal << std::endl;
Node start_node(start, 0.);
Node goal_node(goal, 0.);
float* costs = new float[h * w];
for (int i = 0; i < h * w; ++i)
costs[i] = INF;
costs[start] = 0.;
std::priority_queue<Node> nodes_to_visit;
nodes_to_visit.push(start_node);
int* nbrs = new int[3];
bool solution_found = false;
while (!nodes_to_visit.empty()) {
// .top() doesn't actually remove the node
Node cur = nodes_to_visit.top();
if (cur == goal_node) {
solution_found = true;
break;
}
nodes_to_visit.pop();
int row = cur.idx / w;
int col = cur.idx % w;
bool allowDiag;
// check bounds and find up to eight neighbors: top to bottom, left to right
// can move only right\down\down - right so we can max have 3 neighbours
nbrs[0] = (col + 1 < w) ? cur.idx + 1 : -1; // right
nbrs[1] = (row + 1 < h) ? cur.idx + w : -1; // down
allowDiag = (weights[cur.idx + w + 1] == 14) ? true : false;
nbrs[2] = (allowDiag) ? cur.idx + w + 1 : -1; // down-right
std::cout << "right-bottom node : " << weights[cur.idx + w + 1] << std::endl;
float heuristic_cost;
for (int i = 0; i < 3; ++i) {
std::cout << "neighbours : " << nbrs[i] << " ";
if (nbrs[i] >= 0) {
// the sum of the cost so far and the cost of this move
float new_cost = costs[cur.idx] + weights[nbrs[i]];
if (new_cost < costs[nbrs[i]]) {
// estimate the cost to the goal based on legal moves
if (allowDiag) {
heuristic_cost = linf_norm(nbrs[i] / w, nbrs[i] % w,
goal / w, goal % w);
}
else {
heuristic_cost = l1_norm(nbrs[i] / w, nbrs[i] % w,
goal / w, goal % w);
}
// paths with lower expected cost are explored first
float priority = new_cost + heuristic_cost;
nodes_to_visit.push(Node(nbrs[i], priority));
costs[nbrs[i]] = new_cost;
paths[nbrs[i]] = cur.idx;
}
}
}
std::cout << "\n";
}
delete[] costs;
delete[] nbrs;
//return solution_found;
}
};
int main() {
Astar astarPathfinding;
float* weights;
int h;
int w;
int start;
int goal;
bool diag_ok;
int* paths;
astarPathfinding.setVariables(weights, h, w, start, goal, diag_ok, paths);
astarPathfinding.start(); // error
return 0;
}
You have "start" as member and "start" as function.
Rename one of them will fix your error.

How to round float to up and down value c++ with own function?

double round(double a)
{
double b, c, f, g;
float d[2];
c = modf(a, &b);
if (a > 0) {
f = a - c;
g = a - c + 1;
d[0] = f;
d[1] = g;
return d[0], d[1];
}
else {
f = a - c;
g = a - c - 1;
d[0] = f;
d[1] = g;
return d[0], d[1];
}
}
I need to get 2 numbers it the end(for ex: if I have num 12.34, I want to get 12 and 13)This is my function of rounding for pos and neg numbers. But it returns only 1 value(( So I'm stack...pls, help how to return 2 values?
You cannot return two things in the return, so return d[0],d[1] compiles but doesn't work as you expect. You can use two reference parameters in the function prototype to return. Something like void round(double a, double* result1, double* result2). Into the function, set d[0] to *result1 and d[1] to *result2.
Another thing: Are you sure the line g = a - c - 1; when a is negative is correct? I think you need to do g = a + c - 1;, because a is negative.
#include "pch.h"
#include <iostream>
#include <array>
using namespace std;
auto rounding(double x)
{
int part = static_cast<int>(x);
if (x < 0.0)
{
return array<int, 2> {
part - 1, part
};
}
else
{
return array<int, 2> {
part, part + 1
};
}
}
int main()
{
double x;
cout << "Please, enter a float number to round: ";
cin >> x;
auto r1 = rounding(x);
if (x > 0) {
cout << "A lower value: " << r1[0] << endl << "A bigger value: " << r1[1];
}
else {
cout << "A bigger value: " << r1[0] << endl << "A lower value: " << r1[1];
}
}

Overload in function on a class type

#include <iostream>
#include <iomanip>
#include <cmath>
#include "lineType.h"
using namespace std;
int main()
{
double x, y;
double a = 1.;
double b = 0.;
double c = 1.;
double d = 2.;
double e = 0.;
double f = 3.;
double g = 0.;
double h = 4.;
double i = -1.;
lineType line1(a, b, c);
lineType line2(d, e, f);
lineType line3(g, h, i);
cout << "Line 1: ";
line1.display();
if (line1.isParallel(line2)) cout << "line1 is parallel to line 2" << endl;
if (line1.isPerp(line3)) cout << "line 1 is perpendicular to line 3" << endl;
if (line2.intersect(line3, x, y))
cout << "The intersection of lines 2 and 3 is at point(" << x << ", " << y << ")" << endl;
else
cout << "Lines 2 and 3 do not intersect." << endl;
return 0;
}
This is the code I am testing and the issue I am getting is c2661 no overloaded function takes 3 arguments
My Header file is:
#pragma once
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
class lineType
{
private:
double a;
double b;
double c;
public:
void display() const;
bool isParallel(const lineType& line) const;
bool isPerp(const lineType& line) const;
bool intersect(const lineType& line, double& x, double& y);
lineType();
lineType(double a2, double b2, double c2);
~lineType();
};
This is the lineType.cpp file that was wanted
#include "lineType.h"
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void lineType::display() const
{
cout << a << "x + " << b << "y = " << c << endl;
}
bool lineType::isParallel(const lineType& line) const
{
if (a == 0 && line.a == 0)
return 1;
if (b == 0 && line.b == 0)
return 1;
else if (-a / b == -line.a / line.b)
return 1;
else
return 0;
}
bool lineType::isPerp(const lineType& line) const
{
if (a == 0 && line.b == 0)
return 1;
if (b == 0 && line.a == 0)
return 1;
else if (-a / b == line.b / line.a)
return 1;
else
return 0;
}
bool lineType::intersect(const lineType& line, double& x, double& y)
{
if (a == 0)
x = c / b;
if (line.a == 0)
x = line.c / line.b;
if (b == 0)
y = c / a;
if (line.b == 0)
{
y = line.c / line.a;
}
else
{
x = ((a*line.c) - (c*line.a)) / ((b*line.a) - (a*line.b));
y = ((c*line.b) - (b*line.c)) / ((b*line.a) - (a*line.b));
}
if (a == 0 && line.a == 0)
return 0;
if (b == 0 && line.b == 0)
return 0;
return 1;
}
lineType::lineType()
{
a = 0;
b = 0;
c = 0;
}
lineType::lineType(double a2, double b2, double c2)
{
a = a2;
b = b2;
c = c2;
}
lineType::~lineType()
{
}
The error message that appears
Error (active) E0289 no instance of constructor "lineType::lineType" matches the argument list Project1 line 20
Same error message for lines 21 and 22 in the source.cpp file. so I am not sure what is occuring?
lineType::lineType, which is the constructor, is implicitely generated, since you did not provide any user defined constructors. Default-generated constructors take no arguments, yet you try to provide three arguments in lines:
lineType line1(a, b, c);
lineType line2(d, e, f);
lineType line3(g, h, i);
I suspect you wanted to take advantage of aggregate initialisation, which you can't unfortunately use, since your a, b and c variables are private. You might want to add such constructor yourself:
lineType(const double a, const double b, const double c)
:a(a), b(b), c(c) { }
But that's not all. You have couple more problems with your code. Notably:
if (line1.isParallel(line2)) cout << "line1 is parallel to line 2" << endl;
contains a typo. It should be isParrallel, as declared in your class (which is also a typo) instead of isParallel. Fix either of these.
Lastly, the line:
if (line2.intersect(line3, x, y))
will not compile, since intersect() returns void, not bool. if statements require that they are provided either bools or something that's implicitely convertible to bool type. Make your function return bool, which is the logical assumption for a function that's name starts with is.

working of constructor c++

Help me figure out how the line p1(10,15); works and From where p1 derive from as it was never declared.
I am learning how constructor works
i used this link link
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
When you make an instance of class Point, it automatically call constructor and do the assignment.
Point p1(10, 15);
it's like this:
Point(10, 15)
{
x = 10;
y = 15;
}
and you using 2 functions to get x,y :
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

Returning a boolean value from a Circle Class C++

I am trying to return a boolean value using a C++ class. It needs to be able to check whether circle A is the same size as circle B using an overload operator > which I have added as a public member in the class. In my int main it always seems to return false even when the circles are the same size.
Thanks, in advance.
Circle class:
#include <iostream>
#include <cmath>
using namespace std;
//creating a constant pi that can't be changed
const double pi = 3.14159265;
class Circle
{
//defining the private memeber variables
private:
double radius, xpos, ypos;
//defining the public member variables
public:
//creating a constructor that takes all of the variables
Circle(double r, double xposition, double yposition) {
radius = r;
xpos = xposition;
ypos = yposition;
}
//creating a constructor that takes just the radius
Circle(double r) {
radius = r;
xpos = 0;
ypos = 0;
}
//creating a contructor that initialised everything to 0
Circle() {
radius = 0;
xpos = 0;
ypos = 0;
}
//defining the functions for radius, X-position, Y-position and area
double getRadius() {return radius;}
double getX() {return xpos;}
double getY() {return ypos;}
double getArea() {return pi*radius*radius;}
//creating an overaload operator + to add the various properties of a circle together
Circle operator+(Circle C) {
radius = sqrt(this->getRadius()*this->getRadius() + C.getRadius()*C.getRadius()); //calculates the radius from the area
xpos = (this->getX() + C.getX()) / 2.; //calculating the half way x position
ypos = (this->getY() + C.getY()) / 2.; //calculating the half way y position
return Circle(radius, xpos, ypos);
}
//created an overload operator << that outputs information about the circle in a consistent manor
friend ostream& operator<<(ostream& os, Circle C) {
return os << "radius = " << C.getRadius() << " at (x,y) = (" << C.getX() << "," << C.getY() << ")";
}
bool operator>(Circle C) {
if (this->getRadius() > C.getRadius()) {
return true;
}
else {
return false;
}
}
};
Int main ()
#include "Circle.hpp"
using namespace std;
int main()
{
//defining the circles A and B
Circle A(4.0,2.0,1.0);
cout << "Circle A: " << A << endl;
Circle B(4.0,5.0,6.0);
cout << "Circle B: " << B << endl;
//Adds A and B using the overload operator +
Circle C = A + B;
//Outputs the formatted text using the overload operator <<
cout << "Circle C: " << C << endl;
bool test;
Circle D(4.0,2.0,1.0);
if (A > D) {
test = false;
}
else if (D > A) {
test = false;
}
else {
test = true;
}
cout << boolalpha << test << endl;
return 0;
}
A.r is 4.0. D.r is also 4.0. Neither D > A nor A > D is true. > checks for real greater than. If you want to have greater-or-equal use >= instead.
When you do the following you are changing the value of A's radius
Circle C = A + B
"In my int main it always seems to return false even when the circles are the same size"
It will surely return false when circle are of same size as your condition is:-
if ( this->getRadius() > C.getRadius() )
return true;
everything other than this would return false. If you want to return true when your circle are of same size then make it:-
if ( this->getRadius() < C.getRadius() )
return false;
else
return true;
EDITED IN RESPONSE TO COMMENT:-
Then probably you can use enum if want to to test three different scenarios:-
if ( this->getRadius() > C.getRadius() )
return ENUM_GREATER;
else if ( this->getRadius() == C.getRadius() )
return ENUM_EQUAL;
return ENUM_LESSER;
Your operator+ modifies the left-hand operand. So, this line modifies A :
Circle C = A + B;
(including the radius member). So, by the time you compare A to D, A's radius is no longer 4.0.
The operator+ can be modified as follows to fix this :
Circle operator+(const Circle& C) const {
double r = sqrt(this->getRadius()*this->getRadius() + C.getRadius()*C.getRadius()); //calculates the radius from the area
double x = (this->getX() + C.getX()) / 2.; //calculating the half way x position
double y = (this->getY() + C.getY()) / 2.; //calculating the half way y position
return Circle(r, x, y);
}