If I have a vector like this:
struct vector3D {
float x;
float y;
float z;
};
vector3D aVector = { 3.4, 4.4, 9.3 }; // my vector
How can I cout the aVector to the console?
you can overload the insertion operator << to use for your objects:
struct vector3D {
float x;
float y;
float z;
friend ostream& operator<<(ostream& out, vector3D rhs){
out << "( " << rhs.x << ", " << rhs.y << ", " << rhs.z << " )" << endl;
return out;
}
};
now you can use cout to print your object values:
int main(){
vector3D v = {10, 20, 30};
cout << v << endl;
}
Related
So basically I created two classes for two vectors and got there norms. How would I approach using both classes to find the distance between both vectors in my main function ? I know I can use the friend function but we have not been taught that in class so I have to use the scope :: operator and constructor and destructors. I been trying different things but nothing works any ideas ? I am fairly new to c++.
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
class Vector {
private:
float x;
float y;
float z;
public:
Vector(float xaxis, float yaxis, float zaxis)
{
x = xaxis;
y = yaxis;
z = zaxis;
}
float getx() { return x; }
float gety() { return y; }
float getz() { return z; }
float normVector()
{
float result = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
return result;
}
};
class Vectortwo {
private:
float x;
float y;
float z;
public:
Vectortwo(float xaxis, float yaxis, float zaxis)
{
x = xaxis;
y = yaxis;
z = zaxis;
}
float getx() { return x; }
float gety() { return y; }
float getz() { return z; }
float normVectortwo()
{
float result = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
return result;
}
};
int main()
{
Vector v(2, 2, 2);
v.getx();
v.gety();
v.getz();
v.normVector();
cout << " X axis" << v.getx() << endl;
cout << " Y axis" << v.gety() << endl;
cout << " Z axis" << v.getz() << endl;
cout << " The norm of our first vector " << v.normVector() << endl;
Vectortwo b(3, 3, 3);
b.getx();
b.gety();
b.getz();
b.normVectortwo();
cout << " X axis" << b.getx() << endl;
cout << " Y axis" << b.gety() << endl;
cout << " Z axis" << b.getz() << endl;
cout << " The norm of our first vector " << b.normVectortwo() << endl;
return 0;
}
I know I can use the friend function but we have not been taught that in class [...]
You can always use getx(), gety() and getz() directly to calculate the distance. Since this gets a bit tiresome to write more than once you can write a little function that wraps the calculation:
float distance(Vector v1, Vectortwo v2)
{
return sqrt(
pow(v1.getx() - v2.getx(), 2)
+ pow(v1.gety() - v2.gety(), 2)
+ pow(v1.getz() - v2.getz(), 2)
);
}
It has to be declared before main() (but after Vector and Vectortwo) and could be used like this:
cout << "The distance is " << distance(v, b) << " units." << endl;
Since you somehow declared to vector classes Vector and Vectortwo that are basically identical (apart from the name), you can also just remove Vectortwo and use Vector for both instances, v and b. That would simplify the code and both parameters of the distance() function could be of type Vector.
I have been trying to print the points like The position of the point is (1,2) from using class, but I can't figure out a way to do it. I simply can't find a way to return two numbers like that, but the problem requires solution that way.
#include <iostream>
using namespace std;
class MyPoint{
public:
int x,y,radius;
MyPoint()
{
x=0;
y=0;
}
MyPoint(int x1,int y1)
{
x=x1;
y=y1;
}
int point_display()
{
char st=(x,y);
return st;
}
int getAdd()
{
return x+y;
}
};
int main()
{
MyPoint mypoint;
cin>>mypoint.x>>mypoint.y;
cout<<"The position of the point is "<<mypoint.point_display()<<endl;
cout<<"The sum of the coordinates is "<<mypoint.getAdd()<<endl;
return 0;
}
The usual solution to this is to provide an overload of operator << for class MyPoint to print the point.
Something like this:
#include <iostream>
using namespace std;
class MyPoint{
public:
int x,y,radius;
MyPoint()
{
x=0;
y=0;
}
MyPoint(int x1,int y1)
{
x=x1;
y=y1;
}
int getAdd()
{
return x+y;
}
friend ostream& operator << (ostream& os, const MyPoint& p);
};
ostream& operator << (ostream& os, const MyPoint& p)
{
os << p.x << ", " << p.y;
return os;
}
int main()
{
MyPoint mypoint { 1,2 };
cout<<"The position of the point is "<<mypoint<<endl;
cout<<"The sum of the coordinates is "<<mypoint.getAdd()<<endl;
return 0;
}
Output:
The position of the point is 1, 2
The sum of the coordinates is 3
Live demo
Your point_display could return a string composed of the 2 values:
std::string point_display()
{
return std::string{"("} + std::to_string(x)
+ "," + std::to_string(x) + ")";
}
Alternatively, as your question asks about returning 2 values, the function could return a pair:
std::pair<int,int> point_display ()
{
return {x,y};
}
and in main, you could do:
auto [x, y] = mypoint.point_display();
cout << "The position of the point is ("
<< x << "," << y << ")" << endl;
However, since the data members are public, you could just destructure the object and print out the values in main:
auto [x, y, radius] = mypoint;
cout << "The position of the point is ("
<< x << "," << y << ")" << endl;
If all you want to do is print the coordinates, you could have the method do it:
void point_display()
{
cout << "(" << x << ", " << y << ")";
}
...
cout<<"The position of the point is ";
mypoint.point_display();
cout << endl;
If you really want to return the coordinates, you could have separate accessors ("getters"):
int getX()
{
return x;
}
int getY()
{
return y;
}
or use references:
void getCoordinates(int &rx, int &ry)
{
rx = x;
ry = y;
}
...
int a, b;
mypoint.getCoordinates(a, b);
cout << a << " " << b << endl;
i have the following Vector3D code, and for some reason cin is able to change the object values only once. do you have any idea why?
i guess it's something related to the 'const' definition but i'm not sure.
adding both code (partial) and test
// code:
class Vector3D
{
private:
double _x, _y, _z;
public:
Vector3D() : _x(0), _y(0), _z(0) {};
Vector3D(double x, double y, double z) : _x(x), _y(y), _z(z) {};
Vector3D(const double parm[DIMENSION]) : _x(parm[0]), _y(parm[1]),
_z(parm[2]) {};
const Vector3D operator+(const Vector3D &other) const;
Vector3D &operator+=(const Vector3D &other);
const double &operator[](int idx) const;
double &operator[](int idx);
friend ostream &operator<<(ostream &out, const Vector3D &c);
friend istream &operator>>(istream &in, Vector3D &c);
};
const Vector3D Vector3D::operator+(const Vector3D &other) const {
return Vector3D(*this) += other;
}
Vector3D &Vector3D::operator+=(const Vector3D &other) {
(*this)._x += other._x;
(*this)._y += other._y;
(*this)._z += other._z;
return *this;
}
const double &Vector3D::operator[](int idx) const {
assert(idx >= 0 && idx < DIMENSION);
switch (idx)
{
case 0:
return _x;
case 1:
return _y;
case 2:
return _z;
default:
return _x; // not reachable
}
}
double &Vector3D::operator[](int idx)
{
assert(idx >= 0 && idx < DIMENSION);
switch (idx)
{
case 0:
return _x;
case 1:
return _y;
case 2:
return _z;
default:
return _x; // not reachable
}
}
ostream &operator<<(ostream &out, const Vector3D &c)
{
out << c._x << " " << c._y << " " << c._z;
return out;
}
istream &operator>>(istream &in, Vector3D &c)
{
in >> c._x >> c._y >> c._z;
return in;
}
// test:
void readFromStreamTest(int &tests) {
std::stringstream os;
os << 8.0 << " " << 3.0 << " " << 4.0;
Vector3D a;
os >> a;
os << a; // "8 3 4" as should be
os.str(std::string());
os << 2.1 << " " << 3.1 << " " << 4.1;
os >> a;
os.str(std::string());
os << a;
if (os.str()!=("2.1 3.1 4.1"))
{
std::cerr << "failed. should be 2.1 3.1 4.1 but was " << a;
}
}
test results: "failed. should be 2.1 3.1 4.1 but was 8 3 4" (old values!!)
You cannot use a stringstream like that, after extracting the contain throw os >> you cannot again modify it by os.str(value) nor os << if you don't call os.clear() before, for instance
void readFromStreamTest(int &tests) {
std::stringstream os;
os << 8.0 << " " << 3.0 << " " << 4.0;
Vector3D a;
os >> a;
os.clear();
os << a; // "8 3 4" as should be
os.str(std::string());
os << 2.1 << " " << 3.1 << " " << 4.1;
os >> a;
os.str(std::string());
os.clear();
os << a;
if (os.str()!=("2.1 3.1 4.1"))
{
std::cerr << "failed. should be 2.1 3.1 4.1 but was " << a;
}
}
P.S. I modified your original code to make it compilable
I am having issues displaying coordinates that are read into a class. This is my first time using classes so please be understanding!
Here is what I have so far:
#include <iostream>
using namespace std;
class Vector{
private:
float x;
float y;
public:
Vector(float f1, float f2)
{
x=f1;
y=f2;
}
Vector(){}
float display()
{
Vector v;
cout << "(" << v.x << "," << v.y << ")" << endl;
return 0;
}
};
int main()
{
Vector v1(0.5, 0.5);
cout << "v1 ";
v1.display();
system("pause");
return 0;
}
It prints
v1 (-1.07374e+008,-1.07374e+008)
Your problem is that you are not printing out the coordinates of the Vector you created in main() but a default created one in your function. Instead of
float display()
{
Vector v;
cout << "(" << v.x << "," << v.y << ")" << endl;
return 0;
}
You need
float display()
{
//Vector v; remove this
cout << "(" << x << "," << y << ")" << endl;
// no v.x no v.y
return 0;
}
I suggest you change the default constructor to
Vector() : x(0), y(0) {}
So it would have printed
v1 (0,0)
You should also change
Vector(float f1, float f2)
{
x=f1;
y=f2;
}
To
Vector(float f1, float f2) : x(f1), y(f2) {}
As it is a good habit to get into. This can save resources and CPU cycles when dealing with non POD types. For more information see Why should I prefer to use member initialization list?
the Vector v; line is a mistake. You are basically creating a new uninitialized vector instead of crating your own instance.
one correction would be:
int display()
{
cout << "(" << x << "," << y << ")" << endl;
return 0;
}
since x and y are member of this class
I need to write program as follow:
#include <iostream>
using namespace std;
class Point
{
public:
double X;
double Y;
Point(){}
Point(double x, double y)
{
X = x;
Y = y;
}
};
class Circle
{
public:
Point P;
double R;
Circle(){}
Circle(Point p, double r)
{
P = p;
R = r;
}
Circle operator +(Circle C1, Circle C2)
{
return Circle(C1.Point, C1.R + C2.R);
}
Circle operator -(Circle C1, Circle C2)
{
return Circle(C2.Point, C1.R - C2.R);
}
};
int main()
{
Circle c1, c2, cr1, cr2, ck1, ck2;
// create c1
// create c2
cr1 = c1 + c2;
// display cr1
cr2 = c2 + c1;
// display cr2
ck1 = c1 - c2;
// display ck1
ck2 = c2 - c1;
// display ck2
return 0;
}
Two classes Point and Circle, where Circle have member of Point as it's center, two operators to add and to subtract two Circles.
And I can't compile this, what is wrong?
#################################################################################
EDIT:
After correction it looks like that, and works perfectly:
#include <iostream>
using namespace std;
class Point
{
public:
double X, Y;
Point(){}
Point(double x, double y)
{
X = x;
Y = y;
}
};
class Circle
{
public:
double R;
Point P;
Circle(){}
Circle(Point p, double b)
{
P = p;
R = b;
}
Circle operator+(const Circle& C1)
{
Circle C;
C.P = this->P;
C.R = this->R + C1.R;
return C;
}
Circle operator -(const Circle& C1)
{
Circle C;
C.P = C1.P;
C.R = this->R - C1.R;
return C;
}
};
int main()
{
double X, Y, R;
cout << "Coordinates for C1:" << endl;
cout << "\tX: ";
cin >> X;
cout << "\tY: ";
cin >> Y;
cout << "Radius for C1:";
cin >> R;
Circle *c1 = new Circle(Point(X, Y), R);
cout << "Coordinates for C2:" << endl;
cout << "\tX: ";
cin >> X;
cout << "\tY: ";
cin >> Y;
cout << "Radius for C2:";
cin >> R;
Circle *c2 = new Circle(Point(X, Y), R);
Circle cs1 = c1->operator+(*c2);
Circle cs2 = c1->operator-(*c2);
Circle cr1 = c2->operator+(*c1);
Circle cr2 = c2->operator-(*c1);
cout << "cs1([" << cs1.P.X << ", " << cs1.P.Y << "], " << cs1.R << ")" << endl;
cout << "cs2([" << cs2.P.X << ", " << cs2.P.Y << "], " << cs2.R << ")" << endl;
cout << "cr1([" << cr1.P.X << ", " << cr1.P.Y << "], " << cr1.R << ")" << endl;
cout << "cr2([" << cr2.P.X << ", " << cr2.P.Y << "], " << cr2.R << ")" << endl;
char ch;
cin >> ch;
return 0;
}
When you define operators like operator- inside your class as member functions, then when you use it
C3 = C1 + C2;
The compiler is actually calling your member function like
C3 = C1.operator+(C2);
From this you should be able to figure out that operators as member functions only takes one argument, and that the first object in the operator is the this object.
For stand-alone (non-member) functions they need two arguments.
You might want to check e.g. this reference on operator overloading.
You have incorrect overloaded operators. Look at the following code:
Circle operator +(const Circle& C)
{
return Circle(this->P, this->R + C.R);
}
Circle operator -(const Circle& C)
{
return Circle(this->P, this->R - C.R);
}