I need to create an ADT for an assignment. I have my class definition in a header file as follows:
#ifndef PHONECALL_H
#define PHONECALL_H
#include <iostream>
using namespace std;
class PhoneCall
{
public:
PhoneCall();
PhoneCall(string newNumber);
~PhoneCall();
string getNumber()const;
int getLength()const;
float getRate()const;
float calcCharge(); //calcuates total cost of call
friend bool operator==(const PhoneCall & call1, const PhoneCall & call2);
friend istream& operator >>(istream& in, PhoneCall& call);
friend ostream& operator <<(ostream& out, const PhoneCall& call);
private:
string number;
int length;
float rate;
};
All the bodies of the functions are in the implementation file (no errors there)
Then in the main application file, when I call the calcCharge() function, I get:
error: 'calcCharge()' was not declared in this scope
This is the only error I get. Here is the application file code:
#include <iostream>
#include <fstream>
#include "PhoneCall.h"
using namespace std;
int main()
{
string num, cellNum;
int length;
float rate, total;
cout << "Enter a phone number: " << endl;
cin>> num;
PhoneCall theCall(num);
ifstream read;
while (read >> cellNum >> length >> rate)
{
if (cellNum == num)
{
total += calcCharge();
}
}
return 0;
}
I know the code for the main application is incomplete, but due to this error I am not able to test whether the program is doing what I need it to do.
It's a member of the class.
total += theCall.calcCharge();
Related
I am fairly new to classes. I created a class called Counter which basically creates a counter object and has certain data members and function members associated with it.
The header file for the class is:
#ifndef c
#define c
#include <iostream>
#include <string>
#include <vector>
using std::vector; using std::string; using std::ostream;
class Counter{
int v_;
public:
vector<string> log_;
int initialized_;
Counter(int);
int value();
int get_v() const { return v_; } //getter
void set_v(int val) { v_ = val; } //setter
friend ostream & operator<<(ostream &, Counter &);
friend Counter operator+(const Counter &, const Counter &);
};
ostream & operator<<(ostream &, Counter &);
Counter operator+(const Counter &, const Counter &);
#endif
and the cpp implementation file looks like this:
#include "counter.h"
#include <iostream>
#include <vector>
#include <string>
using std::string; using std::vector; using std::ostream;
Counter::Counter(int a){
v_ = a;
initialized_ = a;
log_.push_back("Constructor called with a " + std::to_string(a));
}
int Counter::value(){
log_.push_back("value called. returned a " + std::to_string(v_));
return (v_--);
}
ostream & operator<<(ostream & out, Counter & c){
c.log_.push_back("<< called."); //line 1
out << "Counter("<< c.initialized_ << ")#" << c.v_; //line 2
return out;
}
Counter operator+(const Counter & c_one, const Counter & c_two){
Counter c_three(c_one.initialized_ + c_two.initialized_);
c_three.set_v(c_one.get_v()+c_two.get_v());
return c_three;
}
When I compile the file I get bombarded with expected primary-expression before ‘.’ token in line 1 and line 2 of the "<<" operator overloaded function. I really have no idea as to why this is happening. Any help?
What is c? You've defined it as nothing and then you use
c.log_.push_back(...)
Which the preprocessor changes to
.log_.push_back(...)
I'm not sure what you're trying to do but the error clearly states it's looking for an expression before the period, where it appears you have none.
I have only one custom class with .h and .cpp files but I get error while trying to create an instance of this class from main.cpp (using IDE clion).
I am just a beginner and reading C++ primer learning class, if there are some inappropriate things please point out.
main.cpp
#include "Fun.h"
void Solve();
int main()
{
Solve();
return 0;
}
void Solve()
{
Sales_data total;
if(read(cin,total)){ //read the first record
Sales_data temp;
while(read(cin,temp)){
if(temp.isbn() == total.isbn())
total.combine(temp);
else{
print(cout,total) << endl;
total = temp;
}
}
print(cout,total);
}//if
else{
cerr << "No data!?" << endl;
}
}
Fun.cpp
#include "Fun.h"
using std::istream;
using std::ostream;
double Sales_data ::avg_price() const {
if(units_sold)
return revenue/units_sold;
else
return 0;
}
Sales_data& Sales_data:: combine(const Sales_data& rhs){
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
istream &read(istream &is,Sales_data &item)
{
double price = 0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;
return is;
}
ostream &print(ostream &os, const Sales_data &item)
{
os << item.isbn() << " " << item.units_sold << " "
<< item.revenue << " " << item.avg_price() ;
return os;
}
Sales_data add(const Sales_data& lhs,const Sales_data& rhs)
{
Sales_data sum = lhs;
sum.combine(rhs);
return sum;
}
Fun.h
#ifndef PROJECT1_FUN_H
#define PROJECT1_FUN_H
#include <cstdio>
#include <cstring>
#include <cassert>
#include <vector>
#include <iostream>
using std::istream;
using std::ostream;
using std :: cin;
using std :: cout;
using std :: cerr;
using std :: endl;
struct Sales_data{
std::string isbn()const{return bookNo;}
Sales_data& combine(const Sales_data&);
double avg_price() const;
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0;
};
Sales_data add(const Sales_data&,const Sales_data&);
istream &read(istream &,Sales_data &);
ostream &print(ostream &,Sales_data &);
#endif //PROJECT1_FUN_H
This is the error information:
I wonder what caused the problem?
I think the problem is that declaration and definition of the print function are different (the Sales_data parameter is a reference in declaration while is a constant reference in definition):
ostream &print(ostream &,Sales_data &); // Fun.h
ostream &print(ostream &os, const Sales_data &item) // Fun.cpp
Change the declaration in the header file to:
ostream &print(ostream &, const Sales_data &);
Hey guys I am trying to overload ifstream and ofstream but without any success.
Header File:
#include <iostream>
#include <fstream>
using namespace std;
class Complex
{
private:
double real;
double imaginary;
public:
//constructors
Complex();
Complex(double newreal, double newimaginary);
~Complex();
//setter
void setReal(double newreal);
void setImaginary(double newimaginary);
//getter
double getReal();
double getImaginary();
//print
void print();
//methods
Complex conjugate();
Complex add(Complex c2);
Complex subtraction(Complex c2);
Complex division(Complex c2);
Complex multiplication(Complex c2);
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1;
return in;
}
};
Test file:
#include <iostream>
#include <fstream>
#include <string>
#include "Complex2.h"
using namespace std;
int main()
{
Complex c1;
ifstream infile;
infile.open("in1.txt");
cout << "Reading from the file" << endl;
infile >> c1;
// write the data at the screen.
infile.close();
return 0;
}
I didnt think the cpp file was important since the header file includes the ifstream.
Everytime I run this program i get this error:
Reading from the file
Segmentation fault (core dumped)
I dont know how to fix it.
Thank you very much.
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1; // This is calling this function infinitely!!
return in;
}
The above code implements the operator>> for the Complex type. However, it is a recursive function with no stopping condition.
You probably should be do something similar to the following. Obviously, I don't know how the class was encoded so this is just for illustration.
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
double real;
in >> real;
c1.setReal(real);
double imaginary;
in >> imaginary;
c1.setImaginary(imaginary);
return in;
}
I overlooked that it's a friend function so this could also work.
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1.real;
in >> c1.imaginary;
return in;
}
As mentioned in my comment, and in the other answer the operator>>() overload is just called recursively.
One of the most common approaches to fix that, is to declare a put() function in your Complex class like:
class Complex {
public:
// ...
private:
double real;
double imaginary;
istream& put(std::istream& is) {
is >> real;
is >> imaginary;
return is;
}
};
And let the global overload call that function:
friend ifstream& operator >> (ifstream& in, Complex &c1) {
return c1.put(in);
}
I have to make a program to display the weather in Sheffield since 1930.
I have to use sheffield.data for the record.
I have 3 files. Data.cpp, Data.hpp and analyze.cpp
analyze.cpp:
#include <istream>
#include <fstream>
#include <vector>
#include "data.hpp"
using namespace std;
int main()
{
MonthData data();
vector<MonthData> vectorData;
ifstream file ("sheffield.data");
string line;
int l_num = 0;
if (file.is_open()) {
while (getline(file, line))
if (l_num < 4) {
l_num += 1;
}
else {
file >> data;
vectorData.push_back(data);
}
float MinimumDeg = vectorData[0].getMinimum();
int year = vectorData[0].getYear();
for ( size_t a = 0; a < vectorData.size(); a++)
{
MinimumDeg = vectorData[a].getMinimum();
year = vectorData[a].getYear();
}
cout << "Lowest year and month lowest rainfall: '\n'" << "Min Temp;" << MinimumDeg << "C '\n'" << "Year" << year << endl;
return 0;
}
}
:
data.cpp
#include "data.hpp"
#include <iostream>
using namespace std;
istream& operator >> (istream& in, MonthData& data)
{
in >> data.year >> data.year >> data.temp_maximum >> data.temp_minimum >> data.air_frost >> data.rain >> data.sun;
return in;
}
data.hpp:
#ifndef DATA_HPP
#define DATA_HPP
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
class MonthData
{
friend istream& operator >> (istream&, MonthData&);
public:
//overload constructor
MonthData(double, int, double, double, int, double, double);
//Accessor functions
double getYear() const { return year; } //returns the year
int getMonth() const { return month; } //returns the month
double getMaximum() const { return temp_maximum; } //returns maximum temperature
double getMinimum() const { return temp_minimum; } //returns minimum temperature
int getFrost() const { return air_frost; } //returns air frost
double getRain() const { return rain; } //returns rainfall
double getSun() const { return sun; } //returns no of hours of sunshine
private:
double year;
double month;
double temp_maximum;
double temp_minimum;
int air_frost;
double rain;
double sun;
};
#endif
Why am I getting this error?
[sc14da#cslin035 cw]$ g++ data.cpp data.hpp analyze.cpp -o analyze
analyze.cpp: In function ‘int main()’:
analyze.cpp:11: error: no matching function for call to ‘MonthData::MonthData()’
data.hpp:17: note: candidates are: MonthData::MonthData(double, int, double, double, int, double, double)
data.hpp:12: note: MonthData::MonthData(const MonthData&)
If you do not provide any constructor in your class, the compiler will automatically create one for you.
In your class, you have specified a particular constructor:
MonthData(double, int, double, double, int, double, double);
As soon as you provide any constructor, the compiler will not create a default constructor (i.e. one that takes no parameters).
You are calling
MonthData data();
You are passing no parameters here but you have no constructor that takes no parameters.
You probably meant to call
MonthData data(with 7 parameters);
Alternatively, add the following to your MonthData class body:
MonthData();
Then in your data.cpp, need to provide the code for what this constructor should do, i.e.
MonthData::MonthData()
{
//Initialise as required - but better to use a member initialization list
}
It would be better to use a member initialization list for your 7 member variables.
For example:
MonthData::MonthData()
: year(2014), month(2), temp_maximum(15.4), temp_minimum(2.1), air_frost(5), rain(5.6), sun(7.6) //Use desired default values
{}
This simple constructor code could instead be put directly in the class body in the header file:
class MonthData
{
public:
//overload constructor
MonthData(double y, int m, double max, double min, int fr, double r, double s)
: year(y), month(m), temp_maximum(max), temp_minimum(min), air_frost(fr), rain(r), sun(s) {};
//default constructor
MonthData()
: year(2014), month(2), temp_maximum(15.4), temp_minimum(2.1), air_frost(5), rain(5.6), sun(7.6) {};
etc
};
In addition - review your variable types. Should year really be a double? Also you have month declared as a double but your accessor returns an int.
That's not surprising as you haven't included a default constructor. Or, more specifically, a constructor that matches this line:
MonthData data();
Solution: add a default constructor in your base MonthData class (data.hpp).
Update: I made Sergii's changes below, but now I get the error: undefined reference to `cs202::operator<<(std::basic_ostream >&, cs202::Rational const&)'. Any ideas how to fix this? Thanks
I would appreciate help figuring out why I am getting this error:
"error: 'output' is not a member of namespace 'cs202'"
I have a class called Rational as follows:
#ifndef RATIONAL_H
#define RATIONAL_H
namespace cs202{
class Rational
{
private:
int m_numerator;
int m_denominator;
public:
Rational(int nNumerator = 0, int nDenominator = 1) {
m_numerator = nNumerator;
m_denominator = nDenominator;
}
int getNumerator(){return m_numerator;}
int getDenominator(){return m_denominator;}
friend std::ostream& operator<<(std::ostream& output, const Rational& cRational);
};
}
#endif
The implementation file for the friend function which overrides the << operator looks like this:
#include "rational.h"
namespace cs202{
friend std::ostream& operator<<(std::ostream& output, const Rational& cRational)
{
output << cRational.m_numerator << "/" << cRational.m_denominator;
return output;
}
}
Finally, Main looks like this:
#include <iostream>
#include "rational.h"
using namespace std;
using namespace cs202;
int main()
{
Rational fraction1(1, 4);
cs202::output << fraction1 << endl;
return 0;
}
I have tried using cout instead of cs202:output, I have tried with and without the namespace cs202 (which is a requirement of the assignment), and I have tried making the operator overload function a member function of the class rather than a friend function to no avail.
What am I missing? Thanks
I suppose you want it out to standard output (to console)
int main()
{
Rational fraction1(1, 4);
std::cout << fraction1 << endl;
return 0;
}
Also you do not need friend here. "Friend" keyword is used only in a class
#include "rational.h"
namespace cs202{
std::ostream& operator<<(std::ostream& output, const Rational& cRational)
{
output << cRational.m_numerator << "/" << cRational.m_denominator;
return output;
}
}
Thanks, I figured it out. I had to change the placement of the {} for the namespace.