I am new to operation overloading. I doing a lab where I need to be able to show the Area and circumference of a circle. The user inputs the radius and the center x,y point. My problem is that I am lost in how to properly execute the operation overload on multiplication. Could some one please help me?
This is the portion of the main.cpp
cout << "====================================================" << endl;
cout << "Radius is: " << circle1.setRadius << endl;
cout << "Area is: " << circle1.setArea << endl;
cout << "Circumference is: " << circle1.setCircumference << endl;
This is my circleTypeImp.cpp
#include <iostream>
#include "circleType.h"
#include "pointType.h"
class CircleType;
const float PI = 3.14;
void CircleType::setRadius (float r)
{
float radius const=r;
}
void CircleType::printCircle() const
{
}
void CircleType::setArea ()
{
return PI * radius * radius;
}
void CircleType::setCircumference ()
{
return 2 * PI * radius;
}
and this is my CircleType.h
#ifndef CIRCLETYPE_H
#define CIRCLETYPE_H
#include "pointType.h"
#include <iostream>
using namespace std;
class CircleType : public PointType
{
public:
void setRadius(float r);
void printCircle() const;
CircleType& operator* (const CircleType& radius);
void setArea();
void setCircumference();
private:
float radius const;
};
#endif
Thank you
Here's what I could come up with to help you out, based on your clarifications.
I've pasted and edited the code you had, and added comments to it when I made changes to detail why those changes where made.
A few of the highlights:
When calling any function, even those without parameters, you still need the ().
Functions that return a value, should not return void but rather the type of the return value. (i.e. float in the cases below).
When you want to set a member variable it's customary to use setVariableName or something similar and when you're returning the value of a member variable (or simple operation on) you can use getVariableName
so as to avoid confusion over what the function should do.
You should avoid using namespace std in header files (.h/.hpp files), so as not to force everyone using your code to also use the same namespaces.
radius shouldn't be declared const as you want to be able to set it's value after creating the object.
when using PI you often want the most accurate representation for your variable type. You can often find this on many systems in cmath as M_PI (#include <cmath>).
I haven't done really anything with the PointType class or the overloaded multiplication operator as 1. I have no clue what the PointType class looks like and the multiplication operator doesn't seem necessary.
Below is a sample program using this class to illustrate how to use the member functions.
CircleType.h
#ifndef CIRCLE_TYPE_H
#define CIRCLE_TYPE_H
#include "PointType.h"
#include <iostream>
// It's common practice to not put "using namespace" in a header file.
// If you do, anyone including your header file has to use it.
class CircleType : PointType {
public:
void setRadius(const float r);
void printCircle() const;
CircleType operator * (const circleType& c) const;
float getRadius() const;
float getArea() const;
float getCircumference() const;
private:
float radius; // Note because you want to set radius
// after creation of a circle object
// radius should not be const
}
#endif
CircleType.cc
#include "CircleType.h" // PointType.h will also be included
#include "PointType.h" // But it's also fine to explicitly include it
#include <iostream>
using namespace std;
// you don't need a dummy class here, In fact that will likely cause a compiler issue
// You should probably use a more accurate value of Pi
const float PI = 3.1415927; // Or use M_PI in "cmath" (if it's defined on your system)
void CircleType::setRadius(const float r){
radius = r;
}
void CircleType::printCircle() const {
// Do whatever you need to print a circle
}
// As far as I can tell, you don't actually need to overload
// multiplication to do any the tasks you mentioned.
CircleType CircleType::operator * (const CircleType& c) const {
CircleType tmp;
// I have no clue what multiplying two circles gives you,
// this is the general form of the multiplication operator
return tmp;
}
// It is customary to name a function that returns a private variable
// or the result of simpler operations on private variables with getXXX
// like the ones below -- Note the return type is not void but
// the actual type you expect.
float CircleType::getRadius() const {
return radius;
}
float CircleType::getArea() const {
return PI * radius * radius;
}
float CircleType::getCircumference() const {
return 2 * PI * radius;
}
main.cc
#include "CircleType.h"
#include "PointType.h"
#include <iostream>
using namespace std;
int main(int argc, char ** argv){
CircleType c1;
float tmp;
cout << "Input radius of circle: ";
cin >> tmp;
c1.setRadius(tmp);
cout << "=============================================" << endl;
// note even for functions that take no parameters, you still need the () to call it
cout << "Radius is: " << c1.getRadius() << endl;
cout << "Area is: " << c1.getArea() << endl;
cout << "Circumference is: " << c1.getCircumference() << endl;
return 0;
}
Related
I am trying to build an optimization library in C++ for parameters optimization.
The problem and the parameters type may vary, e.g. if the problem is to minimize the Ackley Function, then we have a vector<double> of size 2 (index 0 for the x, and index 1 for the y). However, we may have problems where the parameters are integers, or even strings.
Many algorithm exist for this type of optimization, like Genetic Algorithm, Differential Evolution, etc. In most of them, once we modify the parameters based on their optimization strategy, we have to call an evaluation function that receives the parameters, and given a objective function, will return a value (fitness).
My question is how could I implement an abstract class Problem in C++ such that it contains an virtual double evaluate function in which receives as reference a vector of the generic type of the related problem? For example, user's problem should inherit Problem and he needs to specify a type T, in this case, the evaluation function should be like virtual double evaluate(const vector<T> ¶meters){}.
If the strategy which I mentioned above is not feasible for C++. Please, suggest alternatives strategies.
Based on #Quentin comment and your details I would say that you could first declare Problem as a class template
#include <vector>
#include <typeinfo>
#include <iostream>
using namespace std;
template<class T>
class Problem
{
public:
Problem() {
if(typeid(T) == typeid(double)){
cout << "The problem is of type double" << endl;
}
}
virtual double evaluate(const vector<T> &decisionVariables) = 0;
};
Then you can inherit from it and override the evaluate function based on your needs. Since you mentioned Ackley Function, I implemented an AckleyFunction which inherits from Problem with type double
#include "problem.h"
#include "math.h"
using namespace std;
class AckleyFunction : public Problem<double>
{
public:
AckleyFunction() {}
double evaluate(const vector<double> &decisionVariables) override {
const double x = decisionVariables[0];
const double y = decisionVariables[1];
return -20 * exp(-0.2 * sqrt(0.5 * (pow(x, 2) + pow(y, 2)))) - exp(0.5 * (cos(2 * M_PI * x) + cos(2 * M_PI * y))) + exp(1) + 20;
}
};
The global minimum for the Ackley function is x = 0, and y = 0. You can see that bellow in the main.cpp
#include <ackleyfunction.h>
#include <memory>
using namespace std;
int main(int argc, char *argv[])
{
shared_ptr<Problem<double>> prob(new AckleyFunction());
vector<double> decisionVariables = {5.1, 3.3};
cout << "Value at coordinates (5.1, 3.3): " << prob->evaluate(decisionVariables) << endl;
decisionVariables = {0., 0.};
cout << "Value at coordinates (0.0, 0.0): " << prob->evaluate(decisionVariables) << endl;
}
Output:
The problem is of type double
Value at coordinates (5.1, 3.3): 12.9631
Value at coordinates (0.0, 0.0): 0
Would something like this do?
#include <memory>
#include <iostream>
#include <vector>
class Problem {
public:
virtual double evaluate() = 0;
};
class MyProblem : public Problem {
public:
MyProblem(const std::vector<float>& parameters) : mParameters(parameters) {}
double evaluate() override {
// Do evaluation based on mParameters
return 47.11;
}
private:
const std::vector<float>& mParameters;
};
int main() {
std::vector<float> v = {1.0f, 2.0f};
std::unique_ptr<Problem> p{new MyProblem(v)};
std::cout << p->evaluate() << '\n'; // Calls MyProblem::evaluate()
return 0;
}
I have to put overloaded constructor form class Parameters into a function in class Solver.
Here is Parameters Header:
#ifndef Parameters
#define Parameters
#include <iostream>
#include<conio.h>
#include<fstream>
#include<string>
using namespace std;
class Parameters
{
int M;
double dx;
double eps;
public:
Parameters( );
Parameters(int M1, double dx1, double eps1 );
Parameters( string fileName);
};
#endif
The constructor initializes M, dx, eps with default values or chosen by the user from the keyboard or from the file.
I want to have another class which will be containing this initialized values (in order to solve some equation lately, also in this class).
The problem is that although I tried to do this by value, reference or/ pointers, there was always some error or code compiled but done nothing.
Here's my Solver class:
#include "ParametersH.h"
#include "EquationH.h"
#include <iostream>
#include<conio.h>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
class Solver
{
public:
int Solve( Parameters& obj );
};
int Solver::Solve( Parameters& obj)
{
cout << obj.M; // M is private so it fails :<
// another attempt was like this:
Parameters *pointer = new Parameters();
}
int main()
{
Solver Solve();
return( 0 );
}
I really couldn't handle this, hope someone will help.
As #lubgr mentioned in the comments, here
Solver Solve();
you declare a function named Solve() without parameters that give you a Solver object, not the member function Solve( Parameters& obj );
If your goal is to access private members of class Parameters in class Solver: You can either
define Solver a friend of Parameters: See here or
access through setters and getters or
make a struct of Parameters by which you can access everything inside
it
However, it looks like you only need a struct Parameters and a simple function Solve( Parameters& obj);, which will do your job.
struct Parameters
{
int m_;
double dx_, eps_;
Parameters(int M1, double dx1, double eps)
: m_(M1), dx_(dx1), eps_(eps) // provide other contrs as per
{}
};
int Solve(Parameters& obj)
{
std::cout << obj.m_ << " " << obj.dx_ << " " << obj.eps_ << std::endl;
return obj.m_;
}
now in the main() simply:
std::cout << "result: " << Solve(Parameters(1, 2.0, 3.0));
This may be a really easy question but... here it goes. (Thanks in advance!)
I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.
source.ccp
#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply();
system("pause");
exit(1);
}
begin.h
#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
public:
void collectdata();
int test;
};
#endif
begin.cpp
#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
test = 6;
}
calculation.h
#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
public:
void multiply();
};
#endif
calculation.cpp
#include <iostream>
#include "begin.h"
#include "calculation.h"
void calculationclass::multiply()
{
beginclass BEGINOBJECT;
// BEGINOBJECT.collectdata(); // If I uncomment this it works...
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
Simply define member function multiply as
void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
And call it as
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply( BEGINOBJECT );
system("pause");
exit(1);
}
In your code beginclass has no explicit constructor, hence the implicitly defined default constructor will be used, which default constructs all members. Hence, after construction beginclass::test is either 0 or uninitiliased.
What you appear to be wanting is to avoid to call beginclass::collectdata() more than once. For this you would want to set a flag that remembers if beginclass::collectdata() has been called. The member function which returns the data then first checks this flags and, if the flag was not set, calls beginclass::collectdata() first. See also the answer by CashCow.
It looks like you are looking for some kind of lazy evaluation / caching technique whereby a value is calculated the first time it is requested then stored to return it subsequently without having to reevaluate.
In a multi-threaded environment the way to achieve this (using the new standard thread library) is by using std::call_once
If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.
For a "calc_once" example:
class calculation_class
{
std::once_flag flag;
double value;
void do_multiply();
double multiply();
public:
double multiply()
{
std::call_once( flag, do_multiply, this );
return value;
}
};
If you want multiply to be const, you'll need to make do_multiply also const and value and flag mutable.
I've been having this same error for two days now: the best version of my code till now is below, and the compiler keeps complaining that "no operator << matches these operands", though I did #include as was suggested in an other topic.
Also I don't know if I'm supposed to put all there headers and stuff in my post cause it's rather crowded that way..
The whole program isn't really all that relevant, I am trying to create a pure virtual function "vector Toestand (int)" (so it should return a vector and have an int as argument). For some reason this never works and that's why I used an other program of which I was certain it did work and I totally stripped it. Still, no luck so far..
I marked the most important pieces that show at what points c++ disagrees with me
Base class header:
#ifndef BasisToestand_H
#define BasisToestand_H
#include<vector>
using std::vector;
#include <string>
using std::string;
class BasisToestand
{
public:
BasisToestand (const string="geen naam");
virtual ~BasisToestand();
//void setName( const string );
// Get Functions are all declared const
const string getName() const;
virtual const double getVal(double) const = 0; //THIS WORKS
//virtual const vector<double> Toestand(int) const = 0; //THIS DOES NOT
// Overloaded operators is also declared const and virtual
virtual const double operator()(double = 0.) const = 0; //THIS WORKS
private:
string T_Naam;
};
#endif
Base class cpp:
#include <iostream>
using std::cout;
using std::endl;
#include<vector>
using std::vector;
#include <string>
using std::string;
#include <cstdlib>
using std::exit;
#include "BasisToestand.h"
BasisToestand::BasisToestand (const string nieuwe_naam)
: T_Naam(nieuwe_naam)
{
cout << "calling base class BasisToestand constructor for " << T_Naam << endl;
}
BasisToestand::~BasisToestand()
{
cout << "calling base class BasisToestand destructor for " << T_Naam << endl;
}
const string BasisToestand::getName () const
{
return T_Naam;
}
Derived class header:
#ifndef T_Tsunami_H // preprocessor wrapper
#define T_Tsunami_H
#include <string>
using std::string;
#include "BasisToestand.h" // base class header
const static double PI = 3.1415926535897932384626433832795;
class T_Tsunami : public BasisToestand
{
public:
// Constructor with default arguments
T_Tsunami (const double norm = 1., const double mean = 0.,
const double sigma = 1., const string="T_Tsunami");
~T_Tsunami(); // destructor
// Set Functions
void setNorm( const double norm = 1. );
void setMean( const double mean = 0. );
void setSigma( const double sigma = 1. );
// Get Functions are all declared const
const double getNorm() const;
const double getMean() const;
const double getSigma() const;
virtual const double getVal(double) const; //THIS WORKS
//virtual const vector<double> Toestand(int) const; //PROBLEM
// Overloaded operators is also declared const
virtual const double operator()(double = 0.) const; //THIS WORKS
private:
double p0;
double p1;
double p2;
};
Derived class .cpp
#include <iostream>
using std::cout;
using std::endl;
#include <cmath>
#include "T_Tsunami.h" // Only T_Tsunami header file needed
T_Tsunami::T_Tsunami (const double norm, const double mean,
const double sigma, const string nieuwe_naam)
: BasisToestand(nieuwe_naam),
p0(norm),
p1(mean),
p2(sigma)
{
cout << "calling derived class T_Tsunami constructor for " << getName() << endl;
}
T_Tsunami::~T_Tsunami()
{
cout << "calling derived class T_Tsunami destructor for " << getName() << endl;
}
const double T_Tsunami::getVal(double x) const
{
return p0/p2/(sqrt(2*PI))*exp(-pow((x-p1),2)/(2*pow(p2,2)));
}
const double T_Tsunami::operator()(double x) const // overloaded () operator WORKS
{
return getVal(x);
}
void T_Tsunami::setNorm (const double norm)
{
p0 = norm;
}
void T_Tsunami::setMean (const double mean)
{
p1 = mean;
}
void T_Tsunami::setSigma (const double sigma)
{
p2 = sigma;
}
const double T_Tsunami::getNorm() const
{
return p0;
}
const double T_Tsunami::getMean() const
{
return p1;
}
const double T_Tsunami::getSigma() const
{
return p2;
}
//THIS IS WHAT MY VIRTUAL FUNCTION "TOESTAND" SHOULD DO FOR THIS DERIVED CLASS
const vector<double> BasisToestand::Toestand(int GOLF) const
{
vector<double>T_1;
for( int i = 0; i < GOLF; i++ )
{ double y = 0.25*(1-tanh(double(i-75)/5));
T_1.push_back(y);
}
cout<< "Creating vector T_1" << endl;
return T_1;
}
Main function:
#include <iostream>
using std::cout;
using std::endl;
using std::scientific;
#include <string>
using std::string;
#include <cmath>
#include <iomanip>
using std::setw;
using std::setprecision;
#include <vector>
using std::vector;
#include "BasisToestand.h"
#include "T_Tsunami.h"
int main()
{
T_Tsunami myTsunami_1;
BasisToestand *funPtr1 = &myTsunami_1;
BasisToestand& funRef1 = myTsunami_1;
cout << "value at x=0 using pointers is " << funPtr1->getVal(0.) << endl; //WORKS
cout << "value at x=0 using references is " << funRef1(0.) << endl; //WORKS
cout << "Testing Tsunami" **<<** funPtr1->Toestand(10) << endl;
//THIS DOES NOT WORK, the bold thing is where I get the error.
return 0;
}
Your question can be reduced to this:
#include <vector>
#include <iostream>
int main() {
std::vector<int> v;
std::cout << v;
}
main.cpp:5:19: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'std::vector')
And that error pretty much explains the problem. You can't simply send a container to a stream with operator <<. You can either use functionality that someone has written to do this (Pretty-print C++ STL containers), or simply loop over the contents of the vector and do it yourself.
cout << "Testing Tsunami ";
const vector<double>& Toestand = funPtr1->Toestand(10); //get a reference to the vector
for(int i=0; i<Toestand.size(); ++i) //for each element
cout << Toestand[i] << ','; //print the element and a comma
cout << endl;
I have a fairly simple C++ code that doesn't seem to be compiling properly. Essentially, I have some globally defined functions declared in my GLOBAL.HPP file, and are defined in my GLOBAL.CPP file. Then I have a class, EuroOption, that consists of a struct datamember. The class EuroOption has its own member functions that essentially do the same exact thing that the global functions do--so I defined them similarly, and just called global functions inside of the EuroOption member function definitions. Please see below:
//
//GLOBAL.HPP
//
#ifndef GLOBAL_HPP
#define GLOBAL_HPP
#include <iostream>
#include <math.h>
#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions.hpp> // For non-member functions of distributions
using namespace std;
//using namespace boost::math;
namespace GLOBAL // Encapsulate Point in the Global namespace
{
struct EuroOptionData
{
double r; // Interest rate
double sig; // Volatility
double K; // Strike price
double T; // Expiry date
double b; // Cost of carry
};
double n(double x);
double N(double x);
double CallPrice(EuroOptionData od, double S);
double PutPrice(EuroOptionData od, double S);
double PutParity(EuroOptionData od, double S);
double CallParity (EuroOptionData od, double S);
} // Close namespace GLOBAL
#endif
Here is the EuroOption.HPP file:
//
//
//
#ifndef EUROOPTION_HPP
#define EUROOPTION_HPP
#include <string>
#include "Global.hpp"
using namespace std;
using namespace GLOBAL;
class EuroOption
{
private:
public:
struct EuroOptionData od;
//EuroOption class functions
EuroOption(); // Default call option
EuroOption(const EuroOption& option2); // Copy constructor
virtual ~EuroOption(); //Destructor
//EuroOption Global Function Calls
double EuroCallPrice(EuroOptionData od, double S);
double EuroPutPrice(EuroOptionData od, double S);
double EuroCallParity(EuroOptionData od, double S);
double EuroPutParity(EuroOptionData od, double S);
//EuroOption class operators
EuroOption& operator = (const EuroOption& option2); //Assignment Operator
};
#endif
And a snippet of the EuroOption.CPP file:
//
//
//
#include "EuroOption.hpp"
#include <cmath>
#include <iostream>
using namespace GLOBAL;
{
double EuroOption::EuroCallPrice(EuroOptionData od, double S)
{
return CallPrice(od,S);
};
double EuroOption::EuroPutPrice(EuroOptionData od, double S)
{
return CallPrice(od,S);
};
.....
...
}
And finally, a snippet of my Test.CPP file where I test functionality:
//
//
//
#include "Global.hpp"
#include "EuroOption.hpp"
#include <iostream>
using namespace GLOBAL;
int main()
{
EuroOption Batch1; //Initialize EuroOption class object Batch1
cout << "S1: "; double S1; cin >> S1;
cout << "Stock Call Option: " << EuroCallPrice(Batch1.od, S1) << endl;
cout << "Stock Put Option: " << EuroPutPrice(Batch1.od, S1) <<endl;
cout << "Put Call Parity - Call Option:"<< EuroCallParity(Batch1.od, S1)<<endl;
cout << "Put Call Parity - Put Option: "<< EuroPutParity(Batch1.od, S1)<<endl;
//****None of these functions compile. They all state "identifier EuroCallPrice (..etc.) is undefined."
cout << "S1: "; double S1; cin >> S1;
cout << "Stock Call Option: " << CallPrice(Batch1.od, S1) << endl;
cout << "Stock Put Option: " << PutPrice(Batch1.od, S1) <<endl;
cout << "Put Call Parity - Call Option:"<< CallParity(Batch1.od, S1)<<endl;
cout << "Put Call Parity - Put Option: "<< PutParity(Batch1.od, S1)<<endl;
//****These functions all compile properly. They are the original global functions.
I realize this is a lot of code to sift through, but any ideas would be greatly appreciated. As noted in the above code, the original global functions work perfectly, but I want to use the class EuroOption function to call that global function.
Many thanks!
Silly me! All i needed to do was call the EuroCallPrice...etc functions on Batch1.
Thanks for all your help!