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!
Related
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));
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;
}
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'm working on a homework assignment for my C++ class and have ran across a problem that I cannot figure out what I am doing wrong.
Just to note, the separation of the files is necessary and I realize this would be much easier if I just made a structure AttackStyles inside the main and forgo the additional class file altogether.
The base of my problem is that I cannot seem to be able to loop through an array of classes and pull out base data. Here is the code:
// AttackStyles.h
#ifndef ATTACKSTYLES_H
#define ATTACKSTYLES_H
#include <iostream>
#include <string>
using namespace std;
class AttackStyles
{
private:
int styleId;
string styleName;
public:
// Constructors
AttackStyles(); // default
AttackStyles(int, string);
// Destructor
~AttackStyles();
// Mutators
void setStyleId(int);
void setStyleName(string);
// Accessors
int getStyleId();
string getStyleName();
// Functions
};
#endif
/////////////////////////////////////////////////////////
// AttackStyles.cpp
#include <iostream>
#include <string>
#include "AttackStyles.h"
using namespace std;
// Default Constructor
AttackStyles::AttackStyles()
{}
// Overloaded Constructor
AttackStyles::AttackStyles(int i, string n)
{
setStyleId(i);
setStyleName(n);
}
// Destructor
AttackStyles::~AttackStyles()
{}
// Mutator
void AttackStyles::setStyleId(int i)
{
styleId = i;
}
void AttackStyles::setStyleName(string n)
{
styleName = n;
}
// Accessors
int AttackStyles::getStyleId()
{
return styleId;
}
string AttackStyles::getStyleName()
{
return styleName;
}
//////////////////////////////////////////////
// main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "attackStyles.h"
using namespace std;
int main()
{
const int STYLE_COUNT = 3;
AttackStyles asa[STYLE_COUNT] = {AttackStyles(1, "First"),
AttackStyles(2, "Second"),
AttackStyles(3, "Third")};
// Pointer for the array
AttackStyles *ptrAsa = asa;
for (int i = 0; i <= 2; i++)
{
cout << "Style Id:\t" << ptrAsa->getStyleId << endl;
cout << "Style Name:\t" << ptrAsa->getStyleName << endl;
ptrAsa++;
}
system("PAUSE");
return EXIT_SUCCESS;
}
My question is why do I get the error:
"a pointer to a bound function may only be used to call the function"
on both ptrAsa->getStyleId and ptrAsa->getStyleName?
I cannot figure out what is wrong with this!
You are missing () around the function calls. It should be ptrAsa->getStyleId().
You are missing parenthesis on both calls, it should be
ptrAsa->getStyleId()
to call the function.
ptrAsa->getStyleId
is used to refer to a member value / attribute.
You need to invoke the function, not merely reference it:
std::cout << "Style Id:\t" << ptrAsa->getStyleId() << "\n";
std::cout << "Style Name:\t" << ptrAsa->getStyleName() << "\n";
You are Forgot to put () in last in Your Function(ptrAsa->getStyleId ) Calling with arrow operator.