Object declaration Error in eclipse - c++

I have edited previous post to give more complete question so:
I have a class named Heliostat that in the header file i want to make 5 objects.3 of them are from class vector and 2 of them from class targets.The vector class constructors needs as operators Target objects or vector objects. I get error that the program does not recognise the operators as any type. I will give you the code.
I work for an arduino project inside eclipse.
This is the heliostat class header:
#ifndef HELIOSTAT_H_
#define HELIOSTAT_H_
#include "Target.h"
#include "TargetCatalog.h"
#include "vector.h"
#include "Sun.h"
class Heliostat {
private:
public:
double Pitch;
double Azimuth;
Target heliostat(4501472.0,662766.0,1.0);
Target reactor(4501474.0,662768.0,30.0);
Vector sunsVec(Sun::getPitch1year(),Sun::getAzimuth1yearArcsin());
Vector reactVec(heliostat,reactor);
Vector normalVec(reactVec,sunsVec);
Heliostat();
virtual ~Heliostat();
};
#endif /* HELIOSTAT_H_ */
It will have some functions that are not writen know.
The cpp has almost nothing only the constructor that is empty.
The Target class header:
#ifndef TARGET_H_
#define TARGET_H_
class Target {
private:
public:
enum targetlist{Helio,React,Normalpoint};
double gpsX;
double gpsY;
double gpsZ;
Target(double gpsEast, double gpsNorth, double gpsAlt);
virtual ~Target();
};
#endif /* TARGET_H_ */
The vectors class header:
#ifndef VECTOR_H_
#define VECTOR_H_
#include "Target.h"
class Vector {
public:
double easting;
double northing;
double altitude;
Vector(Target startTarget,Target endTarget);
Vector(double targetsPitch,double targetsAzimuth);
Vector(Vector reactorVector,Vector sunVector);
double calculateInclinationAngle(Vector reactorVector,Vector sunVector);
double getPitch(Vector helioNormalVec);
double getAzimuth(Vector helioNormalVec);
virtual ~Vector();
};
#endif /* VECTOR_H_ */
and the vector.cpp:
#include "vector.h"
#include "Maths.h"
#include "Target.h"
//vector::vector() {
// // TODO Auto-generated constructor stub
//
//}
vector::vector(Target startTarget, Target endTarget) {
double eastingTemp=endTarget.gpsX-startTarget.gpsX;
double northingTemp=endTarget.gpsY-startTarget.gpsY;
double altitudeTemp=endTarget.gpsZ-startTarget.gpsZ;
double vecMagnitude=sqrt(pow(eastingTemp,2)+pow(northingTemp,2)+pow(altitudeTemp,2));
easting=eastingTemp/vecMagnitude;
northing=northingTemp/vecMagnitude;
altitude=altitudeTemp/vecMagnitude;
}
vector::vector(double targetsPitch, double targetsAzimuth) {
easting=Maths::cosDeg(targetsPitch)*Maths::sinDeg(targetsAzimuth);
northing=Maths::cosDeg(targetsPitch)*Maths::cosDeg(targetsAzimuth);
altitude=Maths::sinDeg(targetsPitch);
}
vector::vector(vector normReactorVec, vector normSunVec) {
double inclinationAngle=calculateInclinationAngle(normReactorVec,normSunVec);
double normalMagnitude=2*Maths::cosDeg(inclinationAngle);
easting=(normReactorVec.easting+normSunVec.easting)/normalMagnitude;
northing=(normReactorVec.northing+normSunVec.northing)/normalMagnitude;
altitude=(normReactorVec.altitude+normSunVec.altitude)/normalMagnitude;
}
double vector::calculateInclinationAngle(vector reactorVector,vector sunVector) {
double angleResult=(reactorVector.easting*sunVector.easting)
+ (reactorVector.northing*sunVector.northing)
+ (reactorVector.altitude*reactorVector.altitude);
double inclinationAngleDoubled=Maths::arccos(angleResult);
double inclinationAngle=inclinationAngleDoubled/2.0;
return inclinationAngle;
}
double vector::getPitch(vector helioNormalVec) {
double pitch=Maths::arcsin(helioNormalVec.altitude);
if (pitch<0){
pitch=0;
Serial.println(F("error on pitch calc"));
}
return pitch;
}
double vector::getAzimuth(vector helioNormalVec) {
double pitch=getPitch(helioNormalVec);
double theta=Maths::arcsin(helioNormalVec.easting/Maths::cosDeg(pitch));
//taking absolute of theta function abs() get only int as operators
if (theta<0){
theta=-theta;
}
double azimuth;
if (helioNormalVec.easting>0){
if(helioNormalVec.northing>0){
azimuth=theta;
}else if(helioNormalVec.northing<0){
azimuth=180-theta;
}else{
azimuth=90;
}
}else if(helioNormalVec.easting<0){
if(helioNormalVec.northing>0){
azimuth=360-theta;
}else if(helioNormalVec.northing<0){
azimuth=180+theta;
}else{
azimuth=270;
}
}else{
if(helioNormalVec.northing>0){
azimuth=0;
}else if(helioNormalVec.northing<0){
azimuth=180;
}else{
Serial.println(F("error on Azimuth calc"));
}
}
return azimuth;
}
vector::~vector() {
// TODO Auto-generated destructor stub
}
About sun class i just use 2 functions that return doubles.
At this poing there is no sketch i do not expect the program to do something i am verifing it for syntax error.
The error i get says that:
'Sun::getPitch1year' is not a type
The same goes for: getAzimuth1yearArcsin(),TargetCatalog::rectorTarget,TargetCatalog::heliostatTarget,reactVec,sunsVec.
For the first lines at the heliostat header.
Target heliostat(4501472.0,662766.0,1.0);
Target reactor(4501474.0,662768.0,30.0);
i get syntax error that says:expected ',' or '...' before numeric constant
is there any solution about these problems?

In heiliostat.h, the line
Vector sunsVec(Sun::getPitch1year(),Sun::getAzimuth1yearArcsin());
declares a function named sunsVec and should declare what types it takes. The current code tries to call two functions.
Replace Sun::getPitch1year() with the type that function returns, and do the same for Sun::getAzimuth1yearArcsin())

Related

Class function does not take arguments

I am trying to simulate some plasma physics and for that I decided to create my "Simulation world" as a class, defined in "World.h" file:
#ifndef _WORLD_H
#define _WORLD_H
class World{
public:
World(int _Nx, double _x0, double _xf); //Constructor prototype
int _Nx; //Number of nodes
double _dx; //Cell width
void setTime(double _dt, int _num_ts);
protected:
double _x0; //System origin
double _xf; //System ending
double _dt = 0; //time step length
int _num_ts; //number of time steps
};
#endif
The implementation of the class prototypes goes:
#include "World.h"
World::World(int Nx, double x0, double xf)
{
this->_Nx = Nx;
this->_x0 = x0;
this->_xf = xf;
this->_dx = (xf - x0)/(Nx - 1);
//std::cout << Nx;
}
void World::setTime(double dt, int num_ts)
{
this->_dt=dt;
this->_num_ts=num_ts;
}
The problem I am having is that when I call the function "World::setTime(/**/)" from main:
int main()
{
//Create computational system
World world(1000, 0.0, 0.1); //(Nx, x0, xm)
World::setTime(world._dx, 10000);
/*CODE*/
return 0;
}
the compiler shows the message:
[Error] cannot call member function 'void World::setTime(double, int)' without object
Referring to the value of 'int num_ts' given as an argument. What is the prblem? What is the object it is referring to?
I was reading this post:
cannot call member function without object
but I cannot apply the solution in there because I wrote down a constructor in my class. Thank you for your replies!
I think that the problem is that you are calling member function of a defined class instead of an object. To fix that, I would try putting:
World world(1000,0.0,0.1); //(Nx,x0,xm)
world.setTime(world._dx, 10000);
This way you are calling an object that you have defined as "world" of type World.

C++ Object declaration needs another object as parameter

Object-oriented C++ here.
I'm supposed to code a Microwave object that "heats" a FrozenMeal object.
One method of the Microwave object, called void heatMeal(FrozenMeal), is supposed to take an instance of a FrozenMeal object as a parameter and increase its temperature.
FrozenMeal.h
#include <string>
class FrozenMeal {
public:
FrozenMeal(std::string, int);
void setTemperature(double);
std::string getName() const;
int getVolume() const;
double getCoeffizient() const;
double getTemperature() const;
private:
std::string name;
int volume;
double temperature;
double coeffizient;
};
FrozenMeal.cpp
#include <string>
#include "FrozenMeal.h"
using namespace std;
FrozenMeal::FrozenMeal(string mealName, int mealVolu) {
name = mealName;
volume = mealVolu;
temperature = -18;
coeffizient = 0.24;
}
void FrozenMeal::setTemperature(double mealTemp) { temperature = mealTemp; }
string FrozenMeal::getName() const { return name; }
int FrozenMeal::getVolume() const { return volume; }
double FrozenMeal::getCoeffizient() const { return coeffizient; }
double FrozenMeal::getTemperature() const { return temperature; }
Microwave.h
#include "FrozenMeal.h"
class Microwave {
public:
Microwave();
void morePower();
void lessPower();
void setPeriod(double);
void heatMeal(FrozenMeal); // <----------------------------
int getPower() const;
double getPeriod() const;
private:
int power;
double period;
};
Microwave.cpp
#include "Microwave.h"
using namespace std;
Microwave::Microwave() {}
void Microwave::morePower() { if (power < 1000) power += 200; }
void Microwave::lessPower() { if (power > 200) power -= 200; }
void Microwave::setPeriod(double sessionPeri) { period = sessionPeri; }
void Microwave::heatMeal(FrozenMeal mealInst) {
mealInst.setTemperature(80); //example
}
int Microwave::getPower() const { return power; }
double Microwave::getPeriod() const { return period; }
Now, my problem is that my compiler says that the file FrozenMeal.h apparently redefines the object type of FrozenMeal, even though that should be the job of the FrozenMeal.cpp file, and compiling is unsuccessful.
I tried including FrozenMeal.h to Microwave.cpp but that resulted in even more compiler errors.
I feel like I'm doing something horribly wrong here.
Add include guards to your header files so its contents doesn't get included more than once:
FrozenMeal.h:
#ifndef FROZENMEAL_H_INCLUDED
#define FROZENMEAL_H_INCLUDED
// your code ...
#endif /* FROZENMEAL_H_INCLUDED */
Microwave.h:
#ifndef MICROWAVE_H_INCLUDED
#define MICROWAVE_H_INCLUDED
// your code ...
#endif /* MICROWAVE_H_INCLUDED */
Also, you never initialize int Microwave::power and double Microwave::period so you will read and write garbage values in Microwave::morePower() and Microwave::lessPower()
As suggested in the comments, you want to take the parameter of Microwave::heatMeal() by reference so the function can modify the passed object:
void Microwave::heatMeal(FrozenMeal &mealInst)
// ^

Basic Shape class and Circle Class: compiling error

I have this homework assignment to do and I did most of the code, but I have a remaining compiling error in main(), that I do not understand.
Here's the assignment:
Define an abstract base class called BasicShape. The BasicShape class should have the following members (...)
Define a class named Circle. It should be derived from the BasicShape class.
It should have the following members:
a) Private Member Variable: radius (a double used to hold the circle’s
radius)
b) Constructor and Public Member Functions:
Circle(double a, string
n, double r): constructor that should call the base class constructor
to initialize the member area with a and name with n. The constructor
will also set the value of member radius with r
calcArea():
Overridden function (...)
print(): Overridden function (...)
After you have created these classes, create a test program
(...)
And here's my code:
Basic Shape.h
#ifndef BASICSHAPE_H
#define BASICSHAPE_H
#include <string>
class basicShape
{
public:
basicShape(const std::string &, double &);
double getArea() const;
virtual double calcArea() const = 0;
virtual void print()const;
std::string getname()const;
protected:
const double area;
private:
const std::string name;
};
#endif
Circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
#include <string>
#include "Basic Shape.h"
using namespace std;
class Circle : public basicShape
{
public:
Circle(const string & n, double & a, double & r);
virtual double calcArea() const override;
virtual void print() const override;
private:
double radius;
};
#endif
Circle.cpp
#include <iostream>
#include "Circle.h"
#include<string>
using namespace std;
Circle::Circle(const string &n, double &a, double &r)
:basicShape(n,a)
{
radius = r;
calcArea();
}
double Circle::calcArea() const
{
double area;
area = 3.14159*radius*radius;
return area;
}
double basicShape::getArea() const
{
return area;
}
void Circle::print() const
{
cout << "radius:" << radius;
basicShape::print();
basicShape::getname();
}
Test.cpp
#include <iostream>
#include "Basic Shape.h"
#include "Circle.h"
#include <string>
#include<vector>
using namespace std;
void poly(const basicShape * const);
int main()
{
Circle circle("Round",0.0,10.0);
vector< basicShape * > shapes(1);
for (const basicShape *basicshapePtr : shapes)
poly(basicshapePtr);
}
void poly(const basicShape * const baseClassPtr)
{
baseClassPtr->calcArea();
baseClassPtr->print();
}
Here is the compiling error I get in main:
"Circle::Circle(Circle Assignment 3 &&)': cannot convert argument 2 from 'double' to 'double &'
The problem
You try to construct your new circle here:
Circle circle("Round",0.0,10.0);
But your constructor has the following signature:
Circle(const string &n, double &a, double &r)
For the second and third arguments you use references to double values. Passing by reference like this means that you could change the value that is referenced. Unfortunately, you pass constant literals. This is not allowed.
The solution
Either define your constructor by using const references:
Circle(const string &n, const double &a, const double &r)
or, pass by value:
Circle(string n, double a, double r)
Note that the second option seems preferred here. And I'd even advise you to respect the signature given in the assignment, which would have avoided you those troubles.
P.S.: For future questions, please reduce the question to the minimal elements required to reproduce the errors, instead of posting the full assignment and the full code, most of which being not relevant to the error

How to use c++ objects in c?

I have 2 projects decoder and dec in my visual studio. One has C code and other has C++ code using stl respectively.How do I instantiate the c++ classes in my c code inside decode project?
for e.g.
//instantiating object
reprVectorsTree *r1 = new reprVectorsTree(reprVectors1,8);
//using one of its function
r1->decode(code);
What do I need to do for this?
How do I access files from another project?
How do I make use of existing c++ code in C files?
--------edit----------
I have a class like this
class Node//possible point in our input space
{
public:
std::vector<float> valuesInDim;//values in dimensions
std::vector<bool> code;
Node(std::vector<float>value);
Node::Node(float x, float y);
Node::Node(std::vector<float> value,std::vector<bool> binary);
};
How do I use the above class in c++?
If C only allows structs how do I map it to a struct?
Give the C++ module a C interface:
magic.hpp:
struct Magic
{
Magic(char const *, int);
double work(int, int);
};
magic.cpp: (Implement Magic.)
magic_interface.h:
struct Magic;
#ifdef __cplusplus
extern "C" {
#endif
typedef Magic * MHandle;
MHandle create_magic(char const *, int);
void free_magic(MHandle);
double work_magic(MHandle, int, int);
#ifdef __cplusplus
}
#endif
magic_interface.cpp:
#include "magic_interface.h"
#include "magic.hpp"
extern "C"
{
MHandle create_magic(char const * s, int n) { return new Magic(s, n); }
void free_magic(MHandle p) { delete p; }
double work_magic(MHandle p, int a, int b) { return p->work(a, b); }
}
Now a C program can #include "magic_interface.h" and use the code:
MHandle h = create_magic("Hello", 5);
double d = work_magic(h, 17, 29);
free_magic(h);
(You might even want to define MHandle as void * and add casts everywhere so as to avoid declaring struct Magic in the C header at all.)
In simple terms, you just do these:
Write an interface function to convert all the class functions (constructor, destructor, member functions) as pure functions, and encapsulate them as extern "C"{ }
Convert the pointer to the class as pointer to void, and carefully use type-cast wherever you define the "pure functions"
Call the pure functions in the C-code.
For example here is my simple Rectangle class:
/*** Rectangle.h ***/
class Rectangle{
private:
double length;
double breadth;
public:
Rectangle(double iLength, double iBreadth);
~Rectangle();
double getLength();
double getBreadth();
};
/*** Rectangle.cpp ***/
#include "Rectangle.h"
#include <iostream>
extern "C" {
Rectangle::Rectangle(double l, double b) {
this->length = l;
this->breadth = b;
}
Rectangle::~Rectangle() {
std::cout << "Deleting object of this class Rectangle" << std::endl;
}
double Rectangle::getLength() {
return this->length;
}
double Rectangle::getBreadth() {
return this->breadth;
}
}
Now here is my interface to convert the class functions to pure functions. Notice how the pointer to the class is handled!
/*** RectangleInterface.h ***/
#ifdef __cplusplus
extern "C" {
#endif
typedef void * RHandle;
RHandle create_Rectangle(double l, double b);
void free_Rectangle(RHandle);
double getLength(RHandle);
double getBreadth(RHandle);
#ifdef __cplusplus
}
#endif
/*** RectangleInterface.cpp ***/
#include "RectangleInterface.h"
#include "Rectangle.h"
extern "C"
{
RHandle create_Rectangle(double l, double b){
return (Rectangle*) new Rectangle(l, b);
};
void free_Rectangle(RHandle p){
delete (Rectangle*) p;
}
double getLength(RHandle p){
return ((Rectangle*) p)->getLength();
}
double getBreadth(RHandle p){
return ((Rectangle*)p)->getBreadth();
}
}
Now I can use these interface functions in my ".c" file as shown below. I just have to include the RectangleInterface.h function here, and the rest is taken care by its functions.
/*** Main function call ***/
#include <stdio.h>
#include "RectangleInterface.h"
int main()
{
printf("Hello World!!\n");
RHandle myRec = create_Rectangle(4, 3);
printf("The length of the rectangle is %f\n", getLength(myRec));
printf("The area of the rectangle is %f\n", (getLength(myRec)*getBreadth(myRec)));
free_Rectangle(myRec);
return 0;
}
Make wrapper for instantiating C++ objects using C++ exported functions.And then call these functions from C code to generate objects.
Since one is function oriented and other is object oriented, you can use a few ideas in your wrapper:-
In order to copy class member, pass an equivalent prespecified struct from C code to corresponding C++ function in order to fetch the data.
Try using function pointers, as it will cut the cost, but be careful they can be exploited as well.
A few other ways.
you would need to write a wrapper in C.
something like this:
in class.h:
struct A{
void f();
}
in class.cpp:
void A::f(){
}
the wrapper.cpp:
#include "wrapper.h"
void fWrapper(struct A *a){a->f();};
struct A *createA(){
A *tmp=new A();
return tmp;
}
void deleteA(struct A *a){
delete a;
}
the wrapper.h for C:
struct A;
void fWrapper(struct A *a);
A *createA();
the C program:
#include "wrapper.h"
int main(){
A *a;
a=createA();
fWrapper(a);
deleteA(a);
}

Constructor in class with inheritance

I'm having some problems with inheritance and constructors in C++. What I've got is a class VirtualMotor which inherits Motor (is that the correct way to say it?). The class VirtualMotor should have it's own constructor, but I'm doing something wrong when I create it and the compiler gives me an error (se below). My source code is like this:
Motor.h
class Motor
{
protected:
float speed;
float angle;
public:
Motor();
float getSpeed();
float getAngle();
virtual void setSpeed( float speed );
virtual void setAngle( float angle );
Motor.cpp
#include "Motor.h"
float Motor::getSpeed() { return speed; }
float Motor::getAngle() { return angle; }
VirtualMotor.h
#include "Motor.h"
class VirtualMotor: public Motor
{
private:
float lastSpeed;
public:
VirtualMotor();
void setSpeed(float speed);
void setAngle(float angle);
};
VirtualMotor.cpp
#include "VirtualMotor.h"
VirtualMotor::VirtualMotor()
{
speed = 2;
angle = 5;
}
void VirtualMotor::setSpeed(float speed)
{
this->speed = speed;
}
void VirtualMotor::setAngle(float angle)
{
this->angle = angle;
}
Main.cpp
#include <iostream>
#include "VirtualMotor.h"
using namespace std;
int main (int argc, char **argv)
{
VirtualMotor m;
cout << m.getSpeed() << endl;
m.setSpeed(9);
cout << m.getSpeed() << endl;
return 0;
}
To compile I use the command g++ Main.cpp Motor.cpp VirtualMotor.cpp -o main and I get the following error:
/tmp/ccIdYJaR.o: In function `VirtualMotor::VirtualMotor()':
VirtualMotor.cpp:(.text+0x29): undefined reference to `Motor::Motor()'
/tmp/ccIdYJaR.o: In function `VirtualMotor::VirtualMotor()':
VirtualMotor.cpp:(.text+0x5d): undefined reference to `Motor::Motor()'
/tmp/ccIdYJaR.o:(.rodata._ZTI12VirtualMotor[typeinfo for VirtualMotor]+0x8): undefined reference to `typeinfo for Motor'
collect2: ld returned 1 exit status
I feel there's a really simple solution to this, but I just can't see it. I've tried to use VirtualMotor::VirtualMotor() : Motor::Motor() and other variations without any luck.
In your code you declare the Motor() constructor but never provide an implementation for it. Also, you don't seem to be using include guards in your header files. motor.h should look something like this (although this isn't to do with the problem you are asking about):
#ifndef INC_MOTOR_H
#define INC_MOTOR_H
class Motor
{
... // your stuff here
};
#endif
And lastly, protected data is generally a bad idea.
You've declared a default constructor for the class Motor in Motor.h (Motor(); immediately below public:), but you haven't given it a definition in Motor.cpp.
As the others mentioned, Motor()'s definition is missing. The easiest way would be to change its declaration to 'Motor() {}'. This way is cleaner, however:
class Motor {
protected:
Motor(float speed, float angle)
: speed(speed), angle(angle)
{}
public: .
}
...
VirtualMotor :: VirtualMotor
: Motor(2,5)
So you don't have to initialize base class members directly from within VirtualMotor's c'tor.
Add in motor.cpp
Motor::Motor(){
}