Hi, I am going through \"Data structures and Algorithms in C++\" by drozdek, I b
ID: 3888461 • Letter: H
Question
Hi,
I am going through "Data structures and Algorithms in C++" by drozdek, I believe i know HOW to use pointers, but I do not know WHEN,
Could you have a look at this code and help me optimise it?
// drozdek.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <memory>
using namespace std;
class Fraction {
private:
int valuetop=0;
int valuebottom=1;
double decimal=0;
public:
Fraction::Fraction() {
}
Fraction::Fraction(int a, int b):valuetop(a), valuebottom(b), decimal(static_cast<double>(a) / static_cast<double>(b)) {
};
Fraction::~Fraction() {
}
void Fraction::show() {
cout << valuetop << "/" << valuebottom << " or " << decimal << endl;
}
Fraction Fraction::operator+(Fraction &other) const {
unique_ptr<Fraction> result(new Fraction());
result->valuetop = valuebottom*other.valuebottom;
result->valuebottom = valuetop*other.valuebottom + other.valuetop*valuebottom;
result->decimal = (static_cast<double>(result->valuetop) / static_cast<double>(result->valuebottom));
return *result;
}
};
int main()
{
Fraction f1(6,9);
f1.show();
Fraction f2(-3, 9);
f2.show();
cout << endl << "Adding two fractions, result following" << endl << endl;;
Fraction f3 = f2 + f1;
f3.show();
return 0;
}
See if am using a pointer to hold return type but I suspect this is obselete...
Explanation / Answer
Answer:
Here is optimized code :
#include "stdafx.h"
#include <iostream>
#include <memory>
#include<template>
using namespace std;
class Fraction {
private:
int valuetop=0;
int valuebottom=1;
double decimal=0;
public:
template<class T> Fraction::Fraction() {
}
template<class T> Fraction::Fraction(int a, int b):valuetop(a), valuebottom(b), decimal(static_cast<double>(a) / static_cast<double>(b)) {
};
template<class T>Fraction::~Fraction() {
}
template<class T>void Fraction::show() {
cout << valuetop << "/" << valuebottom << " or " << decimal << endl;
}
Fraction Fraction::operator+(Fraction &other) const {
unique_ptr<Fraction> result(new Fraction());
result->valuetop = valuebottom*other.valuebottom;
result->valuebottom = valuetop*other.valuebottom + other.valuetop*valuebottom;
result->decimal = (static_cast<double>(result->valuetop) / static_cast<double>(result->valuebottom));
return *result;
}
};
int main()
{
Fraction f1(6,9);
f1.show();
Fraction f2(-3, 9);
f2.show();
cout << endl << "Adding two fractions, result following" << endl << endl;;
Fraction f3 = f2 + f1;
f3.show();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.