I am new to c++ so I am not sure what I am doing or what's wrong any help ? I am just trying to do a simple equation of motion question where I find the initial velocity of a ball that reaches a max height of 200 meters in 30 seconds. the error in the title is what I keep getting
#include <iostream>
#include <cmath>
struct Ball {
float yf;
float v;
};
using namespace std;
void velocity (Ball b)
{
cout<<"words"<<(b.v = (b.yf - 0.5*9.8*900)/30)<<endl;
return;
}
int main()
{
velocity(Ball b);
return 0 ;
}
The program won't do what you're actually expecting from it. You want the code to call the method that you have defined above the main function. In fact, you don't call it because of a syntactic error.
You need to create a structure instance and utilize it in the method:
Ball b{0.5, 0.3}; // declaring and initializing with some random nums.
velocity(b); // using 'b' (type of Ball)
You did not declare an object of the structure you created.
and used it
Related
It would be ok to define a class like this (ignore its implmentation):
class MyEngine {
private:
int* params;
int param_len;
public:
void set_params(int* _params, int _len);
float get_result(); // relies on `distance` member
float distance; // people can modify this
};
However, if using vector, assume it implicitly includes <iterator> which contains std::distance, how do compiler distinguish std::distance and distance member? (Or will it cause un-expected crash when run?). Say, the function get_result() relies distance member value.
#include <vector>
using namespace std;
class MyEngine {
private:
vector<int> params;
public:
void set_params(int* _params, int _len);
float get_result(); // relies on `distance` member
float distance; // people can modify this
};
update
As people mentioned, using namespace std is bad practice; however, there are still people writing code with using namespace std, and if we are collaborate with them, using their code, is there any concreate example that demonstrate the badness of using namespace std, expecially severe run error? This, would be my real purpose.
There is an answer, saying distinguish the two distance by type. Let's just try this snippet:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iterator>
using namespace std;
class MyEngine {
private:
vector<int> params;
float* distance; // people can modify this
int len;
public:
void setup();
};
void MyEngine::setup()
{
len = 100;
distance = (float*)malloc(sizeof(float)*len);
for(int i=0; i<len; i++) {
distance[0] = len - i;
params.push_back(len-i);
}
int num = distance(params.begin(), params.end());
printf("distance is: %d\n", num);
}
int main(){
MyEngine engine;
int len = 10;
engine.setup();
return 0;
}
Which, would cause compile error saying:
main.cpp:25:23: error: called object type 'float *' is not a function or function pointer
int num = distance(params.begin(), params.end());
~~~~~~~~^
1 error generated.
Demonstrates that it can't distinguish the two distance from their types.
Well, one is MyEngine::distance, and the other is std::distance. They're different names. This is the whole point of scopes.
There is only a problem if you use the unqualified name distance and leave the compiler to figure it out, but if that's not going to work then it'll be because the type of the one chosen doesn't match your usage, so your program won't compile.
If you ever did put things in std then the name can clash in potentially undiagnosable ways, which can cause crashes, and has undefined behaviour per the standard.
The function distance has a different type than the member distance, so the compiler figures that out by the type.
You can even have a function distance(...). As long as parameters are different, they have different type and the compiler figures that out.
Also note that you should not use using namespace std because that also irritates the human reader.
In your updated example, the compiler is indeed confused. You can specify that you want to use the distance function in this case by changing it to int num = std::distance(...);
How do I initialize convert.gram? Whenever I define "gram" in the class decleration the program responds appropriatly. Im trying to put gram in the constructor but its not working. Also am I structuring everything right? Thanks for the help!
Code:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include "math.h"
using namespace std;
struct grams{
grams();
float converter(float pounds);
float gram;
float pounds;
float answer;
};
float grams::converter(float pounds){
answer = pounds * gram;
return answer;
}
grams::grams(){
float convert.gram = 453.592;
}
int main(){
float PtC;
grams convert;
cout<<"Pound to Gram Converter \n";
cout<<"How Many Pounds Do You Want to Convert? \n";
cin>>PtC;
float converter = convert.converter(PtC);
cout<<"Answer = "<<converter<<endl;
return 0;
}
Error:
C:/Users/lisa/Desktop/codelight c++/time_of_for_loop/for_loop_time/for_loop_time/main.cpp:31:13: error: expected initializer before '.' token
What you need to do is just set gram; convert is a instance of grams so its field will be set properly.
grams::grams(){
gram = 453.592;
}
But the more conventional and performant way to initialize class members is to use a member initializer list, like so:
grams::grams() : gram(453.592) {
}
Also, a bit of advice: Because you are using gram as a constant, it would make more sense to set it as a constant instead of a member. You can set it as a static member (and name it better)
struct grams {
static const float GRAMS_PER_POUND = 453.592;
...
You also aren't using the member pound at all; you should consider removing it. There also doesn't make much sense to store answer because you aren't using it via convert after the converter function completes.
This question already has answers here:
constructors basic (reference to distance is ambiguous)
(3 answers)
Closed 7 years ago.
While compiling the following code i am getting the error as
reference to 'distance' is ambiguous
#include<iostream>
using namespace std;
class distance
{
int feet,inches;
distance():feet(0),inches(0)
{
}
distance(int f,int i):feet(f),inches(i)
{
}
void show()
{
cout<<"feet "<<feet;
cout<<endl<<"inches "<<inches;
}
distance operator + (distance) ;
};
distance distance::operator + (distance d)
{
int f,i;
f=feet+d.feet;
i=inches+d.inches;
return distance(f,i);
}
int main()
{
distance d1;
distance d2(2,3),d3(7,5);;
d1=d2+d3;
d1.show();
}
can anyone help me with the error.
And provide me the solution and as to why i am getting this error.
And this is why using namespace std; should not be used. Your class distance is clashing with the standard function std::distance. Get rid of the using namespace std; and if you are going to be using a standard component use std::name_of_thing every time you use it or you can use using std::name_of_thing.
Your class name is clashing with another symbol from the namespace, changing your class name to something else like Distance would be one possible solution.
I've actually managed to successfully do a dynamically allocated array with a normal data type, but it was a while ago (like, six chapters!) And I can't figure out why I can't set the array dynamically here - I know it's giving me an int error, but I can't use the class type because the class type doesn't deal with numbers like that. At this point I'm pretty confused. Here's my code including headers:
#include <iostream>
#include "milTime.h"
#include "Time.h"
using namespace std;
int main()
{
milTime *theta;
bool amOrPm;
int milHr, milSc,milM,times;
cout<<"How many times would you like to convert?";
cin>>times;
theta = new milTime;
*theta = times;
And here's my error:
Error 1 error C2440: '=' : cannot convert from 'int' to 'milTime
*' c:\users\heather\documents\visual studio 2012\projects\military time\military time\source.cpp 17 1 Military Time
Any help would be greatly appreciated, as I'm completely done except for that. Me and my bright ideas to let it be dynamically allocated!
Here's the milTime class that was requested:
#ifndef MILTIME
#define MILTIME
#include <iostream>
#include "Time.h"
class milTime : public Time
{
protected:
int milHours;
int milMins;
int milSeconds;
public:
void setTime(int h)
{
milHours = h;
}
void setMin(int m)
{
milMins=m;
}
void setSec(int s)
{
milSeconds=s;
}
int getmilHours()
{return milHours;}
int getmilMins()
{return milMins;}
int getmilSeconds()
{return milSeconds;}
bool timeConverter(int mTime, int mMins, int mSecs)
{
bool aOrPm;
min = mMins;
if(mTime<12)
{
hour = mTime;
aOrPm = false;
//AM will be false.
}
else if (mTime>12 && mTime<=24)
{
hour = mTime%12+1;
aOrPm = true;
}
sec = mSecs;
return aOrPm;
}
};
#endif
there are already answers why your code doesn't work
just in case you wanted to allocate an array of milTime, you will need to do it like this:
theta = new milTime[times];
this will create times of milTime objects
anyway, you should be using std::vector instead of dynamic allocations, this is much safer
What is the definition of milTime?
You are trying to assign an int, which is an inbuilt integer type, into your own type milTime. Which won't work unless your type has an assignment operator which takes an int.
Does your type have a constructor that takes an int? as in that case you would want something more like:
theta = new milTime(times);
theta is a pointer to miltime but times is an int hence *theta = times; fails.
Here's your problem:
*theta = times;
theta is a class of milTime, times is an int.
You'll probably need to create a setter method in milTime, like this:
theta.setTime( times )
I can't see your milTime class though, can you post it as well?
Well it seems that in this line:
*theta = times;
You try to assign an int to a milTime.
you can fix this by either doing a static cast:
*theta = static_cast<milTime>(times);
Or oldschool cast:
*theta = (milTime) times;
But prefarbly you can add a constructor to milTime (in miltime.h):
milTime(int i) : someInnerDataWhichIsAnInt(i) {}
The last one is preferable as casts are a sign of a bad structure.
To use the last one do this:
theta = new milTime(times);
Or is it because you need an array? Prefaably use:
std::vector<milTimes> theta() // You need to remove prior definition of `theta`.
I am attempting to change a value in a vector which is a variable in a class using a function of a class. When I compile, i get the following errors pointing to the "check[c] = cval;" line:
error C3867: 'acc::check': function call missing argument list; use '&acc::check' to create a pointer to member
error C2109: subscript requires array or pointer type
Note: I have already initialized C to be 0 elsewhere in the program. It might be throwing an error because I am giving the address a variable instead of an integer, but when I substitute the variable with an integer, I still get the same errors.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
class acc
{
public:
void add_Cval(double cval);
private:
vector<double> check(); //vector of all checks
int c; //loop marker for cvals
};
void acc::add_Cval(double cval)
{
check[c] = cval;
c++;
}
vector<double> check(); isn't what you think it is. You just declared a function named check that returns a vector<double>. Get rid of the parenthesis like so vector<double> check;.
Also, your vector<double> is empty, you need to give it some space if you want to do check[c] = cval; (or use check.push_back(cval); instead), allocate the space in the constructor (use "initialization lists" as that is what they are for):
Example:
acc(int vecsize) : check(vecsize), c(0) {}
You might also want to make sure check[c] is a valid position in the vector before assigning anything to it.
check is a method, not a data member, so you need to invoke it - check().
void acc::add_Cval(double cval)
{
check()[c] = cval;
c++;
}
or make it a data member:
class acc
{
public:
void add_Cval(double cval);
private:
vector<double> check; //vector of all checks
int c; //loop marker for cvals
};
The compiler is looking for a function called check() that returns a vector of type double.
private:
vector<double> check(); // A private function that returns a vector of type <double>
Needs to be:
private:
vector<double> check; // A private data member