I want to overload operator *, in this way:
#include <iostream>
using namespace std;
class A{
public:
double liczba;
A operator * (int a){
A b;
b.liczba = this->liczba * a;
return b;
}
};
int main(){
A a;
2*a;
return 0;
}
I get errors, I know that a*2 doesn't cause problems, but how to do 2*a?
You need to declare a friend operator:
class A{
public:
double liczba;
A operator * (int a){
A b;
b.liczba = this->liczba * a;
return b;
}
friend A operator*(int a, A & b);// friend operator
};
A operator*(int a, A & b)
{
return b * a;
}
Ideally, A & b would be const A & b, but you need to declare the operator you already defined to be const as well.
You should declare the operator as a non-member function. For example
A operator * ( const A &a, int x )
{
A b;
b.liczba = a.liczba * x;
return b;
}
A operator * ( int x, const A &a )
{
A b;
b.liczba = a.liczba * x;
return b;
}
Here is a demonstrative program
#include <iostream>
class A{
public:
double liczba;
};
A operator * ( const A &a, int x )
{
A b;
b.liczba = a.liczba * x;
return b;
}
A operator * ( int x, const A &a )
{
A b;
b.liczba = a.liczba * x;
return b;
}
int main()
{
A a = { 10 };
A b = 2 * a * 5;
std::cout << b.liczba << std::endl;
return 0;
}
The program output is
100
You can declare a non-member function:
A operator*( int i, const A & a ) {
A b;
b.liczba = a.liczba * i;
return b;
}
Here's a working example.
Related
I created a class named test having 2 integers. I am trying to overload operator+ for it. But the output is wrong and I can't understand why.
#include <conio.h>
#include <iostream>
using namespace std;
class test
{
int a, b;
public:
test()
{
a = 0;
b = 0;
}
test(int x, int y)
{
a = x;
b = y;
}
test operator+(test t);
void disp()
{
std::cout << "a is =" << a << "\n b is = " << b;
}
};
test test::operator+(test t)
{
test temp;
temp.a = a + t.a;
temp.b = b + t.b;
}
int main()
{
test b1, b2, b3;
b1 = test(10, 20);
b2 = test(30, 40);
b3 = b1 + b2;
b3.disp();
}
You have undefined behavior because your operator+ is not returning temp. You need to do:
test test::operator+(test t)
{
test temp;
temp.a = a + t.a;
temp.b = b + t.b;
return temp; // <- return here
}
Enable all your warnings with something like -Wall, and the compiler will tell you about mistakes like this.
Note that the canonical way of implementing operator+ as a member function is to take the argument by const&, and to make the member function const as well:
test test::operator+(test const &t) const
{
test temp;
temp.a = a + t.a;
temp.b = b + t.b;
return temp;
}
I am trying to understand an output of a short program where operator overloading is used.
The output is 137, where the (2+v).print() outputs 13 and 7 is from v.print();
#include <iostream>
using namespace std;
class V
{
int x;
public:
V(int a = 7, int b = 3) { x = a + b; }
void print() { cout << x; }
V operator+(int n)
{
return x++ + ++n;
}
};
V operator+(int lop, V rop)
{
return rop + lop;
}
int main()
{
V v(1, 6);
(2 + v).print();
v.print();
return 0;
}
I understand the basic concept of the operator overloading and I get that V rop is just a copy of the V v(1,6), and it doesn't change the output of v.print(); where x stays 7, but I don't get why it outputs 13, I always get to 10.
The problem is when trying to return an object of type 'V' from this operator:
V operator+(int n)
{
return x++ + ++n;
}
What you're trying to return here in an 'int' so it should be cast to an object of type 'V', the way it's done (casting from a primitive type to custom class) is using constructors. The only constructor you're having is with 2 optional parameters which creates the problem that it tries to make an object of one parameter only, so it's sent as a = 10, b = 3 (default value) and then the output is 13.
I recommend using multiple constructors to solve the problem if you don't want to change the members of the class.
class V
{
int x;
public:
V() { x = 10; }
V(int a) { x = a; }
V(int a, int b) { x = a + b; }
void print() { cout << x; }
V operator+(int n)
{
return x++ + ++n;
}
};
By this way you can call a default constructor which sets x to 10 as you previously did, another constructor with 1 parameter to cast from 'int' to 'V', and your normal constructor that takes a and b.
In your code when arrive at return (x++ + ++n); compiler create an object V so your constructor will be call again. then these assignment will be occurred a=10 and b=3. So you gotta save a and b values in another members.
Try this :
#include <iostream>
using namespace std;
class V {
int x;
int a;
int b;
public:
V(int a=7, int b=3) { x = a + b; this->a = a; this->b = b; }
void print() { cout << x - this->b; }
V operator+(int n) {
return (x++ + ++n);
}
};
V operator+(int lop, V rop) {
return rop + lop;
}
int main()
{
V v(1,6);
(2 + v).print();
v.print();
return 0;
}
Your (2 + v).print(); output will be 10.
Suppose I have a simple vector class where elements are accessed through a proxy class.
Vector class:
class vec {
public:
vec(int len) {
length = len;
data = new double [len];
}
proxy operator[](int i) {
if (i >= 0 && i < length) {
return proxy(i, data);
}
else {
std::cerr << "AHHHH!\n";
exit(1);
}
}
private:
int length;
double * data;
};
Proxy class:
class proxy {
public:
proxy(int i, double * d) {
index = i;
data = d;
}
void operator=(double rhs) {
data[index] = rhs;
}
private:
int index;
double * data;
};
How can I assign elements from the vector (or rather, from the proxy) to a variable of type double? In other words, how do I accomplish the following:
int main() {
vec a(2);
double x = 3.14;
a[0] = x; // Works!
x = a[0]; // How to make work?
return 0;
}
Unfortunately, I can't write something like:
friend double operator=(double & lhs, const proxy & p) { ... }
since operator= must be a member.
Add a conversion function to your proxy class:
class proxy
{
public:
operator double() const { return data[index]; }
// ...
};
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?
I have made class which represents Line Linia (aX+bY=c) and I overloaded + operator so now it now returns new Linia object which has c = c + b/argument. But the problem is that when I use this operator all the fields of the given Line object become 0
#include <iostream>
using namespace std;
struct Q{
public:
double x,y;
Q(double x, double y){
this->x = x;
this->y = y;
}
friend ostream& operator<< (ostream &wyjscie, Q const& ex){
wyjscie<<"("<<ex.x<<","<<ex.y<<")";
return wyjscie;
}
};
class Linia{
public:
double a,b,c;
Linia (double a, double b, double c){
this->a = a;
this->b = b;
this->c = c;
}
Linia operator+ (double i){
return Linia(a, b, c + i/b);
}
Linia operator- (double i){
return Linia(a, b, c - i/b);
}
Q operator* (const Linia& i){
double w = a*i.b - b*i.a;
double wx = -c*i.b + i.c*b;
double wy = a*(-i.c) + i.c*c;
double x = wx/w, y = wy/w;
cout<<*this<<endl;
cout<<i<<endl;
return Q(x,y);
}
friend ostream& operator<< (ostream &wyjscie, Linia const& ex){
wyjscie<<ex.a<<"x + "<<ex.b<<"y = "<<ex.c;
return wyjscie;
}
};//podwyzszenie przez ile/B
int main()
{
Linia* pionowa = new Linia(0,1,0);
Linia* l = new Linia(1,1,3);
// Q q = (*l) * (*pionowa);
cout<<"linia przed podniesieniem "<<*l<<endl;
// cout<<"punkt przeciecia przed podniesieniem: "<<q<<endl;
l = l+3;
cout<<"Line highered"<<*l<<endl;
l = l-3;
cout<<"Line Lowered "<<*l<<endl;
// q = (*l) * (*pionowa);
// cout<<"punkt przeciecia po podniesieniu: "<<q<<endl;
cout << "Hello world!" << endl;
return 0;
}
You are doing pointer arithmetic here. That means that l ends up pointing to some address where is shouldn't:
Linia* l = new Linia(1,1,3);
l = l+3; // l is a pointer!!!
If you stop using new and raw pointers everywhere it might just work.
int main()
{
Linia pionowa(0,1,0);
Linia l(1,1,3);
l = l+3;
cout<<"Line highered"<< l <<endl;
l = l-3;
cout<<"Line Lowered "<< l <<endl;
}