I have the following code to read a text file using a class definition. I created the TermGrade.h file and the TermGrade.cpp file. But I get few errors:
In the TermGrade.h file I get the warning that it cannot find a definition for any of the defined functions ( Readdata, MidsemesterScore, FinalScore and LetterGrade) even though I have them defined in the .cpp file.
However, the main problem is that in the TermGrade.cpp file I get the error "Error:No instance of overloaded function "getline" matches the argument list" and it also complains that identifier "inLine" is undefined, but it does not complain about inLine in the next statement, but that statement says that both
dataLines[lineNumber] are undefined! Do I need to define these variables in the .cpp file? Any help would be greatly appreciated.
Thank you,
Bill.
// TermGrade.h file
#ifndef TERMGRADE_H
#define TERMGRADE_H
#include <string>
#include<iostream>
#include<fstream>
using namespace std;
class TermGrade {
public:
TermGrade(string fileName) {};
string StudentID;
int assignments;
int exam1;
int exam2;
int final;
bool records = true;
private:
string inLine;
string dataLines[100];
int lineNumber = 0;
bool Readdata(istream& in); // Read line of data from input file
double MidsemesterScore() const; // Calculates average
double FinalScore() const; // Calculates average
char LetterGrade() const; // Determines grade
}; // end class Termgrade
#endif
// TermGrade.cpp file
#include "TermGrade.h" // TermGrade class definition
#include<iostream>
#include<fstream>
TermGrade::TermGrade(string fileName) {
ifstream infile;
infile.open(fileName);
}
bool Readdata(istream& infile)
{
if (!infile.eof)
{
getline(infile, inLine);
dataLines[lineNumber] = inLine;
return true;
}
return false;
}
double MidsemesterScore()
{
return 0.0;
}
double FinalScore()
{
return 0.0;
}
char LetterGrade()
{
return 'a';
}
In the TermGrade.h file I get the warning that it cannot find a
definition for any of the defined functions ( Readdata,
MidsemesterScore, FinalScore and LetterGrade) even though I have them
defined in the .cpp file.
No, you don't have them defined in the .cpp file. You do not have, for example a definition of TermGrade::Readdata method. That method is not defined anywhere. You do have a function called Readdata in there, but that has nothing to do, whatsoever, with the TermGrade::Readdata method.
Regarding a few of the other errors you're getting:
You are calling a function called getline(), however you have not defined that function anywhere, and that's why you are getting that compiler error. Perhaps you meant to refer to the std::getline() function, from the C++ library, if so then that's what you should be referring to.
Also, you are passing a reference to a class called istream, unfortunately you did not define this class anywhere. If you meant to refer to the std::istream class, then you should've referenced it, as such.
However, the std::istream class does not have a member called eof. It does have an eof() method, though.
Related
A program im writing successfully runs on the IDE visual studio code. However, when attempting to use the Bitvise SSH client to run my program I get a list of errors that I myself cannot understand the problem for. Bitvise it another way to access the CMD client from a remote server, for all intenstive purposes it acts the same as windows CMD. I will provide a screen cap of the errors and a full run down of the parts of my program that I believe are causing the errors. If any further code is required please feel free to ask.
errors screen cap
This error report shows a common error, with something being a placeholder for all instances.
multiple definition of `something' /tmp/ccBhjFYn.o:(.bss+0x0): first defined here
This error DOES NOT happen in visual studio code
From this error report it can be seen the issue is found within driver.cpp and my header.h file. For this reason i wont provide a minimal code for these files, but they are small enough to not require one.
MAIN
int main()
{
Customer c;
Part p;
Builder b;
const string fileName = "Parts.txt";
auto partsVec = readpartFile();
auto customerVec = readcustomerFile();
auto builderVec = readbuilderFile();
fexists(fileName);
complexity(c, partsVec);
robotComplexity(partsVec,customerVec);
writeFile(buildAttempt(b, complexity(c, partsVec), variability(customerVec, builderVec)));
return 0;
}
HEADER FILE
#include <vector>
#include <string>
struct Customer {
std::string customerName;
std::string projectName;
std::string listofParts;
} myCustomer;
struct Part {
char partCode;
std::string partName;
int maximum;
int minimum;
int complexity;
} myPart;
struct Builder {
std::string builderName;
int ability;
int variability;
} myBuilder;
bool fexists(const std::string filename);
std::vector<Part> readpartFile();
std::vector<Customer> readcustomerFile();
std::vector<Builder> readbuilderFile();
float complexity(const Customer& c, const std::vector<Part>& parts);
void robotComplexity(const std::vector<Part>& vecB, const std::vector<Customer>& vecC);
double variability(const std::vector<Customer>& customerList, const std::vector<Builder>& builderList);
std::vector<double> buildAttempt(Builder b, double variaiblity, double complexityRobot);
void writeFile(std::vector<double> build);
Thankyou for any help. This question may be hard to understand and follow but i did try my best. Any sugguestions to help improve this question are welcome but please be friendly :)
This in header.h
struct Customer {
std::string customerName;
std::string projectName;
std::string listofParts;
} myCustomer;
Is a definiton of a global variable myCustomer. As such it does not belong in a header file.
Change the header file to this
struct Customer {
std::string customerName;
std::string projectName;
std::string listofParts;
};
extern Customer myCustomer; // global variable declaration
Then to one of your cpp files (I suggest implementation.cpp) add this
Customer myCustomer; // global variable definition
Or you could just do away with global variables completely (the best solution).
NOTE in some of my comments above, I said you have global variable declarations in your header file. What I meant was you have global variable definitions in your header file. The difference between a definition and a declaration is what is crucial here. It's fine to put declarations in a header file, it's wrong to put a definition. Sorry for any confusion.
I'm reading the book "a complete guide to c++". I think there is a typo there on page 252. So I have three files as the following.
In file account.h,
// account.h
// Defining the class Account. class definition (methods prototypes) is usually put in the header file
// ---------------------------------------------------
#ifndef _ACCOUNT_ // if _ACCOUNT_ is not defined
#define _ACCOUNT_
#include <iostream>
#include <string>
using namespace std;
class Account
{
private:
string name;
unsigned long nr;
double balance;
public: //Public interface:
bool init( const string&, unsigned long, double);
void display();
};
#endif
// _ACCOUNT_
In file account.cpp,
// account.cpp
// Defines methods init() and display().
// ---------------------------------------------------
#include "account.h" // Class definition
#include <iostream>
#include <iomanip>
using namespace std;
// The method init() copies the given arguments
// into the private members of the class.
bool Account::init(const string& i_name,
unsigned long i_nr,
double i_balance)
{
if( i_name.size() < 1)
return false; // check data format to make sure it is valid
name = i_name;
nr = i_nr;
balance = i_balance;
return true;
}
// the method display() outputs private data.
void Account::display()
{
cout << fixed << setprecision(2)
<< "--------------------------------------\n"
<< "Account holder:" << name << '\n'
<< "Account number:" << nr << '\n'
<< "Account balance:" << balance << '\n'
<< "--------------------------------------\n"
<< endl;
}
And finally, in file account_t.cpp
// account_t.cpp
// Uses objects of class Account.
// ---------------------------------------------------
#include "account.h" // header file which contains class definition; (prototype for member functions)
int main()
{
Account current1, current2; // create two instances with name current1, current2
current1.init("Cheers, Mary", 1234567, -1200.99);
// have to call the init function to initialize a Account object; init function is public; members properties are private;
// that's why can not do current1.name = "nana" outside of the class definition
current1.display();
// current1.balance += 100; // Error: private member
current2 = current1;
current2.display();
current2.init("Jones, Tom", 3512347, 199.40);
current2.display();
Account& mtr = current1; // create a reference, which points to object current1
mtr.display();
return 0;
}
I do not think it's correct; because obviously there is no way to get access the init member methods and the display member methods, right? I hope this is not a naive question.
EDIT: I tried to run the main function in file account_t.cpp, and got the following output.
~$ g++ account_t.cpp
/tmp/ccSWLo5v.o: In function `main':
account_t.cpp:(.text+0x8c): undefined reference to `Account::init(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned long, double)'
account_t.cpp:(.text+0xb6): undefined reference to `Account::display()'
account_t.cpp:(.text+0xd5): undefined reference to `Account::display()'
account_t.cpp:(.text+0x132): undefined reference to `Account::init(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned long, double)'
account_t.cpp:(.text+0x15c): undefined reference to `Account::display()'
account_t.cpp:(.text+0x176): undefined reference to `Account::display()'
collect2: error: ld returned 1 exit status
Any more comments are greatly appreciated.
There is no issue with what you are asking about. init and display are declared public in the definition of class Account and the file with the class definition is #includeed properly in the .cpp using these methods.
In order to use a function only its declaration is needed (which is in the class definition in the header which is included). The definition/implementation in the .cpp file is not needed to use the function.
Each .cpp is compiled individually (called a translation unit) and afterwards each use of a function (for which only the declaration might have been available) is linked to the correct definitions from the other translation units if necessary via the function's scope, name and signature. This is called the linking process.
An introductory book to C++ should explain how compilation and linking process work.
For g++, there is an easy way to compile all .cpp files individually as translation units and then directly link them together:
g++ account_t.cpp account.cpp
You always need to add all .cpp to the compiler invocation like that. (There are alternative ways, but this is the easiest one.)
However, as mentioned in the comments there are other issues with this program:
_ACCOUNT_ is a reserved identifier that one may not #define in a program. All identifiers starting with an underscore followed by a capital letter are reserved. Using them causes undefined behavior.
using namespace std; is bad, at the very least when used in a header file, see Why is "using namespace std;" considered bad practice?.
Classes have constructors. One should not write init methods in most cases. The constructor is responsible for constructing and initializing class instances. But no constructor is used in the code.
Money should never be stored in double, because arithmetic with double is imprecise. You should store the value in an integer type in dimensions of the smallest relevant unit of money (e.g. cents).
#include <iostream> is not needed in the header file. One should avoid adding #includes that are not needed.
init returns a boolean indicating successful initialization. But main never checks that value. If a function can fail with an error value, then you must check that error value returned by the function to make sure that continuing the rest of the program is safe.
Some of these points may be excusable as simplification for a beginner program, depending on how far the book got at this point (though 200+ pages should already cover a lot), but others aren't.
Example of constructor use doing the same thing:
class Account
{
private:
string name;
unsigned long nr;
double balance;
public: //Public interface:
Account(const string&, unsigned long, double);
void display();
};
Account::Account(const string& i_name,
unsigned long i_nr,
double i_balance)
: name(i_name), nr(i_nr), balance(i_balance)
{
}
int main()
{
Account current1("Cheers, Mary", 1234567, -1200.99);
// Create Account instance and initialize private members; constructor is public; members properties are private;
// that's why can not do current1.name = "nana" outside of the class definition
current1.display();
// current1.balance += 100; // Error: private member
Account current2 = current1; // Create second Account instance and copy private members from first one
current2.display();
current2 = Account("Jones, Tom", 3512347, 199.40); // Replace instance with a copy of a new one
current2.display();
Account& mtr = current1; // create a reference, which points to object current1
mtr.display();
return 0;
}
The i_name.size() < 1 check (which is weirdly written, why not i_name.size() == 0?) would be realized by throwing an exception from the constructor:
Account::Account(const string& i_name,
unsigned long i_nr,
double i_balance)
: name(i_name), nr(i_nr), balance(i_balance)
{
if(i_name.size() == 0) {
throw invalid_argument("Account does not accept empty names!");
}
}
This requires #include<stdexcept> and is a more advanced topic.
This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.
I'm having trouble implementing a state machine for class. I keep getting the errors:
state.cpp:5: error: have0 was not declared in this scope
state.cpp:10: error: redefinition of State* Have0State::process(std::string)
state.h:18: error: virtual State* Have0State::process(std::string) previously defined here
I'm trying to get the Have0State to work before I continue onto the rest of the machine, hence the sparse code.
state.h:
#ifndef STATE_H
#define STATE_H
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
class State{
public:
State(){};
virtual State* process(std::string input) = 0;
};
class Have0State: public State {
public:
Have0State():State(){};
virtual State* process(std::string input);
}have0;
#endif
state.cpp:
#include "state.h"
using namespace std;
State *currentState = &have0;
State* Have0State::process(string input){
if(input == "quarter"){
cout << "cool" << endl;
}
return &have0;
}
int main(int argc, char** argv) {
string input;
//get input
cin >> input;
while (input != "exit") {
currentState = currentState->process(input);
//get input
cin >> input;
}
return 0;
};
I've tried defining the process function as Have0State::State::process(string input) but that didn't work either. Any clarification on how function pointers are supposed to work, especially in the context of subclass member functions, I would greatly appreciate it.
EDIT: Also, what exactly is the have0 declaration at the end of the Have0State class declaration in the state.h file? It doesn't have an explicitly stated type; is it implied that it is of type Have0State??
There aren't any function pointers in your example. Also, like Marciej, I am able to compile (and run) this code.
But, since you asked, the 'have0' declaration simply declares an instance of the class. A class definition can be followed by 0 or more of these declarations (as well as initializers):
class Thing {...} one, another, many[3] = { Thing(1), Thing(2), Thing(3) };
the same as for any other type:
int counter = 0, flag = 0x80, limit = 500;
The possibility of this optional declarator list is why class, struct, union, and enum definitions must be followed with a semi-colon (to terminate the list).
But, as Karthik said, defining a variable in a header will cause "duplicate definition" errors at link time, if the header is included in more than one .cpp file. IMO it's fine though to use this technique to define and declare private objects in a .cpp file (rather than a .h file).
I'm trying to do up a screen scraping assignment. My cpp works, but I don't know how to integrate my unit testing. I tried to do a bool check unit test for the file validity but it's giving me this error:
error: cannot call member function 'bool ScreenScrape::getFile()' without object
screenscrape.cpp:
#include "screenscrape.h"
using namespace std;
int main()
{
ScreenScrape ss;
int choice;
...
...
ss.matchPatternTest();
}
screenscrape.h:
class ScreenScrape
{
public:
ScreenScrape();
void parserTest(int choice);
void matchPatternTest();
void setIndexValue(string data, string IndexName);
void setIndexChange(string data);
void setIndexPercent(string data);
void setIndexDate(string data);
bool getFile();
private:
string IndexName;
string IndexValue;
string IndexChange;
string IndexPercent;
string IndexVID;
string IndexCID;
string IndexPID;
string IndexDate;
};
bool ScreenScrape::getFile()
{
string file1 = "yahoofinance.htm";
char* file2 = new char [file1.size()+1]; // parse file for c string conversion
strcpy(file2, file1.c_str()); // converts to c string
ifstream fin;
fin.open(file2);
if(fin.good())
return true;
else
return false;
}
screenscrapetest.cpp:
#include "screenscrapetest.h"
#include "screenscrape.h"
CPPUNIT_TEST_SUITE_REGISTRATION (ScreenScrapeTest);
void ScreenScrapeTest::fileTest()
{
CPPUNIT_ASSERT(ScreenScrape::getFile()); // test file validity
}
screenscrapetest.h:
#ifndef _SCREENSCRAPETEST_H
#define _SCREENSCRAPETEST_H
#include <cppunit/TestCase.h>
#include <cppunit/extensions/HelperMacros.h>
#include "screenscrape.h"
class ScreenScrapeTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE (ScreenScrapeTest);
CPPUNIT_TEST (fileTest);
CPPUNIT_TEST_SUITE_END ();
public:
void fileTest();
};
#endif
I tried to declare "ScreenScrape ss;" under screenscrapetest.h, use an object (ss) to call getFile() but it's giving me multiples of this error:
/home/user/NetBeansProjects/Assignment1/screenscrape.h:259: multiple definition of `ScreenScrape::getFile()'
I only want to check for file validity with unit testing. Any help will be appreciated.
Thanks in advance!
Regards,
Wallace
bool ScreenScrape::getFile() is not static, so cannot be called as a static function. You'll need to either (a) declare it as static or (b) create an instance of ScreenScrape and call getFile() from it.
Looking at the code, it's not obvious why this function is a method of the class but perhaps it's still in the early stages of development. It can also be refactored to remove lots of redundant code:
bool ScreenScrape::getFile()
{
std::ifstream fin("yahoofinance.htm");
return fin.good();
}
Don't forget your include guards in screenscrape.h:
#ifndef SCREENSCRAPE_H
#define SCREENSCRAPE_H
// Class declaration here...
#endif//ndef SCREENSCRAPE_H
And consider moving the implementation of getFile to the cpp source file. These two steps will prevent you getting the "multiple declaration" errors.
This will fix your compilation errors, but checking for file validity is not a responsibility of a unit test. Unit tests should not interact with the filesystem.
If you're going to be calling ScreenScrape::getfile()rather than ss.getfile(), then getfile() needs be defined as static. The error you're getting is because non-static methods need to be called on a specific object.
It's difficult to track down the error with your version that defines a ScreenScrape object and then uses that to call getfile(); you obviously haven't included all the relevant code since your screenscrape.h file doesn't have 259 lines, and you also haven't shown the revised code in which you "use an object (ss) to call getFile()".