Passing vector to member function of class - c++

I am trying to pass a vector to a member function, but keep coming up with these errors:
27 28 [Error] 'double equip::calcmass' is not a static member of 'class equip'
13 19 [Error] invalid use of non-static data member 'equip::time'
27 24 [Error] from this location
28 1 [Error] expected unqualified-id before '{' token
How can I correct this?
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
class equip
{
public:
vector <double> time;
vector <double> mass;
vector <double> velocity;
vector <double> height;
double calcmass();
double calcvelocity();
double calcheight();
double calctmax();
private:
double T = 7000;
double g = 32.2;
double K = 0.008;
};
double equip::calcmass(time);
{
int i = 0;
for(i=0; i<time.size(); i++)
{
return mass[i] = (3000 - 40 * time[i]) / g;
}
}
int main()
{
int i = 0;
ifstream infile;
string filename;
cout<<"Enter input file name for time (t): ";
cin>>filename;
infile.open(filename.c_str());
while(infile.fail())
{
cerr<<"Error opening file. \n";
cout<<"Enter file name: ";
cin>>filename;
infile.open(filename.c_str());
}
for(i=0; i<time.size(); i++)
{
infile>>time[i];
}

Your code is not working because you defined a a class equip, but never created an instance of it in main, and then you try to read a file content into a member of class time. Also, your function calcmass in the class definition has no arguments, but later you declare it with argument of undetermined type time. Remove the argument of a function, it will see time anyway as they are both members of the same class.

Related

How to Define CountProbation() function using Functions from other Files?

I have been racking my brain on how to properly define the function CountProbation() properly in the Course.css file. I know that a for and if loop should probably be included but I am having trouble including functions from other files, even though I am including a header tag at the beginning of the current Course.css file.
Below are the C++ files that are given in the lab:
NOTE: Only the Course.cpp file is the one that needs to be edited. All of the other files are READ ONLY and purely for your information as the reader.
Sorry if it seems like a lot of code, but I didn't just want to include the Course.cpp file because then you might not understand the program.
Here are the compiler Errors/Warnings:
Course.cpp: In member function ‘int Course::CountProbation()’:
Course.cpp:8:18: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<Student>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]
8 | for (int i=0; i < roster.size(); ++i) {
| ~~^~~~~~~~~~~~~~~
Course.cpp:9:9: error: ‘GetGPA’ was not declared in this scope
9 | if (GetGPA() < 2.0) {
| ^~~~~~
Course.cpp
#include <iostream>
#include "Course.h"
#include "Student.h"
using namespace std;
int Course::CountProbation() { //This is the function that I have tried to define as you can see by my
int probCount; //code
for (int i=1; i < roster.size(); ++i) {
if (GetGPA() < 2.0) {
probCount = probCount + 1;
}
}
return probCount;
}
void Course::AddStudent(Student s) {
roster.push_back(s);
}
Course.h (READ ONLY)
#ifndef COURSE_H
#define COURSE_H
#include <vector>
#include "Student.h"
class Course {
public:
int CountProbation();
void AddStudent(Student s);
private:
vector<Student> roster; //collection of Student objects
};
#endif
Main.cpp (READ ONLY)
#include <iostream>
#include <string>
#include "Course.h"
using namespace std;
int main() {
Course course;
int probCount;
// Example students for testing
course.AddStudent(Student("Henry", "Cabot", 3.2));
course.AddStudent(Student("Brenda", "Stern", 1.1));
course.AddStudent(Student("Lynda", "Robison", 2.4));
course.AddStudent(Student("Jane", "Flynn", 1.8));
probCount = course.CountProbation();
cout << "Probation count: " << probCount << endl;
return 0;
}
Student.h (READ ONLY)
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
// Class representing a student
class Student {
public:
Student(string first, string last, double gpa);
double GetGPA() ;
string GetLast();
private:
string first; // first name
string last; // last name
double gpa; // grade point average
};
#endif
Student.cpp (READ ONLY)
#include "Student.h"
// Student class constructor
Student::Student(string first, string last, double gpa) {
this->first = first; // first name
this->last = last; // last name
this->gpa = gpa; // grade point average
}
double Student::GetGPA() {
return gpa;
}
string Student::GetLast() {
return last;
}
This loop (as it was coded in the original question, before it was edited):
for (int i=1; i < roster.size(); ++i) {
if (Student.GetGPA() < 2.0) {
probCount = probCount + 1;
}
}
is flawed for three reasons:
i should start from 0, rather than 1
i should be of type size_t, rather than int
Student is a type, not a variable
A nice way to solve all these problems is to use a ranged for loop, like this:
for (Student &student : roster)
{
if (student.GetGPA() < 2.0)
probCount = probCount + 1;
}
As mentioned in the comments, you also need to initialise probCount to zero before entering the loop:
int probCount = 0;
Finally, it's worth noting that the above loop would normally be coded as:
for (const Student &student : roster)
{
...
but that won't work here as GetGPA is not declared as a const method. Thanks to #user4581301 for pointing this out.

Using member function to solve equation C++

I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I get these two errors and can't seem to figure out how to get rid of them. Any suggestions are much appreciated, thank you.
23 8 [Error] prototype for 'double equip::calcmass(double)' does not match any in class 'equip'
13 10 [Error] candidate is: double equip::calcmass()
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstring>
using namespace std;
class equip
{
public:
double mass[999999999], velocity, height, time[999999999];
double calcmass();
private:
double T = 7000;
double g = 32.2;
double K = 0.008;
};
double equip::calcmass(double time)
{
int i = 0;
for(i=0; i=999999999; i++)
{
return mass[i] = (3000 - 40 * time[i]) / g;
}
}
int main()
{
int i = 0;
equip rocket;
ifstream infile;
string filename;
cout<<"Enter input file name for time (time): ";
cin>>filename;
infile.open(filename.c_str());
while(infile.fail())
{
cerr<<"Error opening file. \n";
cout<<"Enter file name: ";
cin>>filename;
infile.open(filename.c_str());
}
for(i=0; i<999999999; i++)
{
infile>>rocket.time[i];
}
for(i=0; i<999999999; i++)
{
cout<<rocket.mass[i];
}
return 0;
}
In your class definition you've declared
double calcmass()
In the definition of the member function it's
double calcmass(double time)
They do not match. One takes a double as argument and the other does not.
You were missing a bunch of headers, and in the function declaration was missing the parameter presents in the function definition:
#include <cmath>
#include <cstring>
#include <fstream>
#include<iostream>
using namespace std;
class equip
{
public:
...
double calcmass(double time); // here was missing the parameter
...
};
double equip::calcmass(double time)
{
...
}
Also you are doing time[i] on time which is a double, so you can't use operator[]... If you want to pass an array, you can use pointer to double:
class equip{
...
double calcmass(double* time)
}
double equip::calcmass(double* time)
{
...
}

C++ class instance declaration no matching function

I'm practicing OOP in C++ and I'm creating a bank account class. Here is the class definition:
#include <iostream>
#include <cmath>
#include <limits>
#include <string>
#include <cstring>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
using namespace std;
const int acc_num_length = 8;
const int acc_id_num_length = 13;
class bankAccount {
private:
int acc_num; // account number
int acc_id_num; // account holder ID number
string acc_tel_no; // account holder telephone number
string acc_first_name; // account holder first name
string acc_last_name; // account holder last name
public:
/* constructor */
bankAccount() {
acc_num = 0;
acc_id_num = 0;
acc_tel_no = "";
acc_first_name = "";
acc_last_name = "";
}
/* detail retrieval */
int get_acc_num() {
return(acc_num);
}
int get_acc_id_num() {
return(acc_id_num);
}
string get_acc_tel_no() {
return(acc_tel_no);
}
string get_acc_first_name() {
return(acc_first_name);
}
string get_acc_last_name() {
return(acc_last_name);
}
};
Now in my main program I'm trying to declare an instance of this class,
int main() {
float acc_num = 0;
while ( ((cout << "Enter account number: ") && !(cin >> acc_num)) || (floor(acc_num) < acc_num) ) {
cout << "Invalid account number.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int acc_num_int = acc_num;
string acc_num_string = to_string(acc_num_int);
while ( acc_num_string.length() != acc_num_length ) {
cout << "Invalid account number (8 characters only).\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> acc_num;
cout << "Enter account number: \n";
}
bankAccount ba1 = bankAccount(acc_num_int,0, "","","");
bankAccount ba2 = bankAccount();
return 0;
}
Now everything works except my instance declarations,
C:/Cartrack/C++/Creating a form/Form/main.cpp: In function 'int
main()': C:/Cartrack/C++/Creating a form/Form/main.cpp:68:67: error:
no matching function for call to 'bankAccount::bankAccount(int&, long
long int, const char [1], const char [1], const char [1])'
bankAccount ba1 = bankAccount(acc_num_int,0, "","","");
^ C:/Cartrack/C++/Creating a form/Form/main.cpp:25:2: note: candidate:
bankAccount::bankAccount() bankAccount() { ^~~~~~~~~~~
C:/Cartrack/C++/Creating a form/Form/main.cpp:25:2: note: candidate
expects 0 arguments, 5 provided C:/Cartrack/C++/Creating a
form/Form/main.cpp:16:7: note: candidate:
bankAccount::bankAccount(const bankAccount&) class bankAccount {
^~~~~~~~~~~ C:/Cartrack/C++/Creating a form/Form/main.cpp:16:7: note: candidate expects 1 argument, 5 provided
C:/Cartrack/C++/Creating a form/Form/main.cpp:16:7: note: candidate:
bankAccount::bankAccount(bankAccount&&) C:/Cartrack/C++/Creating a
form/Form/main.cpp:16:7: note: candidate expects 1 argument, 5
provided mingw32-make.exe[1]: * [Form.mk:97: Debug/main.cpp.o] Error
1 mingw32-make.exe[1]: Leaving directory 'C:/Cartrack/C++/Creating a
form/Form' mingw32-make.exe: * [Makefile:5: All] Error 2
====1 errors, 6 warnings====
I'm not sure why there's no matching call. I'm passing it two ints and three strings, which seems to be the mistake most people make when I've read through the existing threats.
Can anyone help please?
Thanks!
Zane
You need to declare parameterized constructors as per your need. All you have is default(or zero-argument) constructor.
Please read the constructor section of any C++ book/tutorial.
Moreover, you should not create objects like
bankAccount ba1 = bankAccount(acc_num_int,0, "","","");
Above statement will create a nameless object and do copy construction of ba1. Please read about copy constructors. When you need a single object this is an overload for extra function call. Instead you can create your object like below
bankAccount ba1(acc_num_int,0, "","","");

How to pass array of input from an external file into main program?

I am new to C++ and i'm having trouble with my program using classes and inputfile to display my input in the output. How should I display the country, population and area? I'm getting error messages like:
Line 82 [Error] invalid use of 'Country::Country'
Line 89 [Error] invalid types 'long int[int]' for array subscript
Line 93 [Error] invalid types 'double[int]' for array subscript
Here is what I have so far:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Country
{
private:
string name;
long int population;
double area;
public:
Country();
Country(string, long, double);
void setName(string);
void setPopulation(long);
void setArea(double);
string getName();
long getPopulation();
double getArea();
};
Country::Country(){
name="?";
population=0;
area=0;
}
Country::Country(string name1, long population1, double area1){
name=name1;
population=population1;
area=area1;
}
void Country::setName(string name1){
name=name1;
}
void Country::setPopulation(long population1){
if(population1>=0.0)
population=population1;
else{
population1=0.0;
cout<< "Invalid number. Setting population to 0."<<endl;
}
}
void Country::setArea(double area1)
{
if(area1>=0.0)
area=area1;
else{
area1=0.0;
cout<< "Invalid number. Setting area to 0."<<endl;
}
}
string Country::getName(){
return name;
}
long Country::getPopulation(){
return population;
}
double Country::getArea(){
return area;
}
int main(){
Country home;
const int H=5;
string homename="";
long homepopulation=0;
double homearea=0;
ifstream infile("mycountrydata.txt");
home.setName(homename);
home.setPopulation(homepopulation);
home.setArea(homearea);
home.Country(homename, homepopulation, homearea);
for(int i=0; i<H; i++){
cout<<"Enter the country's name: ";
infile>>homename[i];
cout<<endl;
cout<<"Enter the country's population: ";
infile>>homepopulation[i];
cout<<endl;
cout<<"Enter the country's area: ";
cout<<endl;
infile>>homearea[i];
}
infile.close();
return 0;
}
A constructor is a special member function which cannot be directly invoked this way:
home.Country(homename, homepopulation, homearea);
long's don't have the [] operator defined and hence you can't do:
infile>>homepopulation[i];
since earlier you declare long homepopulation. The same explanation holds for the error in
infile>>homearea[i];
These are answers addressing the exact errors in your code, but it isn't a substitute for a good teaching resource. See this answer for some useful material.
country is a constructor and it can be invoked by giving the below statement in the beginning of the main() replacing country home;
country home(homename, homepopulation, homearea);
I guess you want to use homepopulation and homearea as arrays but you declared them as normal variables.

How to create a vector of class objects in C++?

I am trying to create a simple stack using vector in C++.
Here is the code:
#include <vector>
class Site
{
public:
int i; // site position i (x-axis)
int s; // site state
vector<Site> neighbors;
Site(void);
Site(int ii, int ss);
void AddNeighbor(Site &site);
};
Site::Site()
{
i = -1;
s = -1;
vector<Site> neighbors;
}
Site::Site(int ii, int ss)
{
i = ii;
s = ss;
}
void Site::AddNeighbor(Site &site)
{
neighbors.push_back(site);
}
void testStack()
{
int tot = 600;
vector<Site> myStack();
int i = 0;
while (i < tot)
{
Site site(i, 1);
myStack.push_back(site);
i++;
}
i = 0;
while (i < tot)
{
Site *site = myStack.back();
myStack.pop_back();
cout << site->i << site->s << endl;
i++;
}
}
Compiler errors:
ising_wolff.cpp: In function ‘void testStack()’:
ising_wolff.cpp:373:17: error: request for member ‘push_back’ in
‘myStack’, which is of non-class type ‘std::vector()’
myStack.push_back(site);
^ ising_wolff.cpp:380:30: error: request for member ‘back’ in ‘myStack’, which is of non-class type ‘std::vector()’
Site *site = myStack.back();
^ ising_wolff.cpp:381:17: error: request for member ‘pop_back’ in ‘myStack’, which is of non-class type
‘std::vector()’
myStack.pop_back();
What do these errors mean?
Here are some sites I have looked at:
1) Creating objects while adding them into vectors
2) push_back causing errors in C
3) how to create vectors of class object
How to create a vector of class objects in C++?
Start with something simpler so you can get the hang of it.
First, create a vector of primitive ints:
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> sites(5);
sites.push_back(5);
for(int x = 0; x < sites.size(); x++){
cout << sites[x];
}
cout << endl;
return 0;
}
Compiling it:
g++ -o test test.cpp
Running it:
./test
000005
Create a vector of class objects in a similar way as above:
#include <iostream>
#include <vector>
using namespace std;
class Site {
public:
int i;
};
int main() {
vector<Site> listofsites;
Site *s1 = new Site;
s1->i = 7;
Site *s2 = new Site;
s2->i = 9;
listofsites.push_back(*s1);
listofsites.push_back(*s2);
vector<Site>::iterator it;
for (it = listofsites.begin(); it != listofsites.end(); ++it) {
cout << it->i;
}
return 0;
}
Which should print:
79
vector<Site> myStack();
This is actually a function declaration. The function is called myStack and it returns a vector<Site>. What you actually want is:
vector<Site> myStack;
The type of neighbours at the moment will store copies of the objects, not references. If you really want to store references, I recommend using a std::reference_wrapper (rather than using pointers):
vector<reference_wrapper<Site>> neighbors;
vector<Site> myStack();
This is wrong. Lose the ().
You're declaring a function, not a vector.
Just write:
vector<Site> myStack;
You could use:
vector<Site> myStack;
myStack.resize(100); //will create 100 <Site> objects