I'm making a car design program. For this program, we are making a class in a header file, and then we will use that header file in our main program by including the file using #include "name of header".
This is my professors header. This is the code in his header. We were instructed to do the header like he is.
/*
Program 14-2
author - Ray Warren, modified from Language Companion
last updated - 19 July 2013
*/
#include <string>
using namespace std;
class CellPhone
{
private:
// Field declarations
string manufacturer;
string modelNumber;
double retailPrice;
public:
// Constructor
CellPhone(string manufact, string modNum, double retail)
{
manufacturer = manufact;
modelNumber = modNum;
retailPrice = retail;
}
// Member functions
void setManufacturer(string manufact)
{
manufacturer = manufact;
}
void setModelNumber(string modNum)
{
modelNumber = modNum;
}
void setRetailPrice(double retail)
{
retailPrice = retail;
}
string getManufacturer()
{
return manufacturer;
}
string getModelNumber()
{
return modelNumber;
}
double getRetailPrice()
{
return retailPrice;
}
}; //end class
This is the program he used the header file in (as you see he included the header file).
/*
Program14-2
author - Ray Warren, modified from Language Companion
last updated - 19 July 2013
*/
#include <iostream>
#include <cstdlib>
#include "CellPhone.hpp"
using namespace std;
int main()
{
// Create a CellPhone object and initialize its
// fields with values passed to the constructor.
CellPhone myPhone("Motorola", "M1000", 199.99);
// Display the values stored in the fields.
cout << "The manufacturer is "
<< myPhone.getManufacturer() << endl;
cout << "The model number is "
<< myPhone.getModelNumber() << endl;
cout << "The retail price is "
<< myPhone.getRetailPrice() << endl;
system("Pause");
return 0;
} //end main
This is my header file containing my class.
#include <string>
using namespace std;
Car(int ym, string mk)
{
yearModel=ym;
make=mk;
speed=0;
}
void setYearModel(int ym)
{
yearModel=ym;
}
void setMake (string mk)
{
make=mk;
}
int returnYearModel()
{
return yearModel;
}
string returnMake()
{
return make;
}
int returnSpeed()
{
return speed;
}
void accelerate()
{
speed += 5;
}
void brake()
{
This is my main program with me attempting to include the header file into my main program. When I tried to compile this, my header file popped up in a new code blocks IDE tab, and gave me this list of errors.
http://prntscr.com/bzu4x5 <--------- list of errors
I have no idea what I'm doing wrong. From what I see, I copied my professor exactly as he told us to, and I'm still getting errors.
Does anyone have any ideas of what's causing this massive list of errors?
#include <string>
#include <iostream>
#include "Car header.h"
int main()
{
}
Your "header file" contains the definitions of the class member functions. It should actually be a .cpp file. What you are missing is a definition of the class itself, and declarations of the member functions.
Note that your professor's sample header file defines the member functions inside the class definition. This is actually poor practise, but he may not have got round to teaching you how do define functions out of line yet.
If you are going to define the functions out of line, you will also need to change the functions to some thing like:
std::string Car::returnMake()
{
return make;
}
Note: "using namespace std" is also poor practise. Professional C++ code tends to be explicit, and use the "std::" prefix. Just get in the habit and save yourself hours of pain.
You did not actually define a class in you header file. Notice that in your teacher's header file, he has:
class Cellphone // -> this is what you do not have
{
private:
// Field declarations
string manufacturer;
string modelNumber;
double retailPrice;
public:
//constructor function
CellPhone(string manufact, string modNum, double retail);
// Member functions
void setManufacturer(string manufact);
void setModelNumber(string modNum);
void setRetailPrice(double retail);
string getManufacturer();
string getModelNumber();
double getRetailPrice();
}
You should have you fields and member functions inside your class. Hope that helps
Related
Below is code for a simple book list with a class to store book names and isbn numbers into an overloaded function using a vector. This program runs fine and I can test it by returning a specific name (or isbn) using an accessor function from my class.
Question: I tried calling (instantiating?) a constructor with parameters from my class but it would not work, so I commented it out. Yet I was still able to run the program without error. From my main below - //BookData bkDataObj(bookName, isbn);
From watching tutorials, I thought I always had to make an object for a specific constructor from a class that I needed to call? My program definitely still uses my overloaded constructor and function declaration BookData(string, int); without making an object for it in main first.
Thanks for any help or input on this matter.
Main
#include <iostream>
#include <string>
#include <vector>
#include "BookData.h"
using namespace std;
int main()
{
string bookName[] = { "Neuromancer", "The Expanse", "Do Androids Dream of Electric Sheep?", "DUNE" };
int isbn[] = { 345404475, 441569595, 316129089, 441172717 };
//BookData bkDataObj(bookName, isbn); //how did program run without instantiating object for class?
vector <BookData> bookDataArr;
int arrayLength = sizeof(bookName) / sizeof(string);
for (int i = 0; i < arrayLength; i++) {
bookDataArr.push_back(BookData(bookName[i], isbn[i]));
}
cout << "Book 4 is: " << bookDataArr[3].getBookNameCl(); //test if works
return 0;
}
BookData.h
#include <iostream>
#include <string>
using namespace std;
class BookData
{
public:
BookData();
BookData(string, int); //wasn't I supposed to make an object for this constructor in my main?
string getBookNameCl();
int getIsbnCl();
private:
string bookNameCl;
int isbnCl;
};
BookData.cpp
#include "BookData.h"
BookData::BookData() {
bookNameCl = " ";
isbnCl = 0;
}
BookData::BookData(string bookNameOL, int isbnOL) { //how did I use this function
bookNameCl = bookNameOL; //definition without an object in main?
isbnCl = isbnOL;
}
string BookData::getBookNameCl() { //can still return a book name
return bookNameCl;
}
int BookData::getIsbnCl() {
return isbnCl;
}
I'm currently defining a few properties for a class in C++ but I'm running into trouble when using type string as opposed to something like int or double. For example:
private:
int LOT;
public:
int getLOT() {
return LOT;
}
void setLOT(int value) {
LOT = value;
}
works fine, but:
private:
string name;
public:
string getName() {
return name;
}
void setName(string value) {
name = value;
}
throws these errors:
https://s26.postimg.org/wm5y7922h/error.png
The file (a header) looks something like this:
#include "general.h" // a header which includes all my other #includes
// which, yes, does include <string>
class MyClass
{
private:
string name;
public:
string getName() {
return name;
}
void setName(string value) {
name = value;
}
// other properties similar to the above
}
The purpose is to access the variable like this:
cout << "Enter your name: ";
cin >> MyClass.setName();
cout << "\nHello, " << MyClass.getName();
// although this isn't exactly how it'll be used in-program
If anyone could provide help with what I'm doing wrong or a better way to go about a string property (as, like I mentioned before, other types work fine) it would be greatly appreciated. Thanks.
string is part of std namespace.
You must use std::string instead of string or add using namespace std; (what I would not recommend you to do in your header file, read "using namespace" in c++ headers).
I want to get a specific object in a class in C++. I looked into multiple sites and it seems my question is unique. Okay here's my code.
In House.h
#include <string>
using namespace std;
class House
{
string Name;
int Health;
public:
House(string a, int h);
void GetHouseStats();
void DamageHouse(int d);
~House();
};
in House.cpp
#include "House.h"
#include <iostream>
House::House(string a, int h)
{
Name = a;
Health = h;
}
void House::DamageHouse(int d) {
Health -= d;
cout << "Your " << Name << " has " << Health << " left."<<endl;
}
void House::GetHouseStats() {
cout << Name<<endl;
cout << Health;
}
House::~House()
{
}
in Source.cpp
#include <iostream>
#include "House.h"
using namespace std;
int main()
{
House Kubo("Bahay Kubo", 2);
Kubo.DamageHouse(1);
}
I have House Kubo as my first object. I would like to save the person's houses into a file but my problem is How can I pass the object's name into the function so that save its data into a file? I can manually place the Kubo and do so as
PlayerHouse = Kubo.Name;
But what if I don't know which house I should save? Like instead of typing down
PlayerHouse = Apartment.Name;//2nd house
PlayerHouse = Modern.Name;//3rd house
Can I use an function argument to place the object's name into PlayerHouse? Like this
void SetHouseName(type object){
PlayerHouse = object.Name;
}
Few ways in which this can be done .. is keeping all created object in a container and then access access the container to get the object in and pass it a function which will write it to a file .
Also if you do not want to maintain the container what you have mentioned about using the function will also work fine
Of course, but if you are going to save the Name of the house anyway, why don't you just ask for a std::string in the first place and then pass the Name to that function?
void SetHouseName(std::string name)
{
PlayerHouse = name;
}
If this is outside your House class you need to create a method to expose the Name member of House though, or just make it public.
To answer your initial question, just as how you would pass built-in types, you can do the same for your House type :
void SetHouseName(House house)
{
PlayerHouse = house.Name;
}
I have spent a great deal of time in google trying to figure out how to pass a vector when using .h and .cpp files between a call in main and a function in an includes block. I was successful using class definitions.
Now everything is going fine until I want to create an overloaded function. (I could have done this with two different classes, but I must use one overloaded function in my program.)
Here is my writeData.h file:
#ifndef WRITEDATA_H
#define WRITEDATA_H
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class writeData
{
public: writeData();
public: writeData(vector<int> & DATAFILE);
public: writeData(vector<int> & DATAFILE, string);
};
#endif
The placement of the using namespace std; is another topic.
Here is my writeData.cpp file:
#include "writeData.h"
writeData::writeData()
{
std::cout << "Default writeData" << std::endl;
}
writeData::writeData(vector<int> & DATAFILE)
{
cout << "writeData 1" << endl;
for (int var : DATAFILE)
{
cout << var <<endl;
}
}
writeData::writeData(vector<int> & DATAFILE, string fileName)
{
ofstream myfile(fileName);
cout << "writeData" << endl;
if (myfile.is_open())
{
for (int var : DATAFILE)
{
cout << var << endl;
myfile << var << endl;
}
myfile.close();
}
}
And here is my main function:
#include <iostream>
#include <vector>
#include <string>
#include "writeData.h"
using namespace std;
int main()
{
string fileName = "test.txt";
vector<int> items{ 10, 14, 22, 34 };
writeData();//default
///////////////////////////////////////////////////
// the next line is the problem code:
//writeData(items);//writes to screen only
//<<When I uncomment it the compiler Tosses the following:
// 'items': redefinition; different basic types
////////////////////////////////////////////////////
writeData(items, fileName);//writes to screen and to file
cin.ignore();
cin.get();
}
The offending line is writeData(items);
Any assistance or pointers to online articles would be most appreciated.
The immediate issue is that this declaration
writeData(items);
is the same as
writeData items;
hence the redefinition error. The deeper issue is that you have defined three constructors for a class, and seem to be attempting to call them without making a named instance. To succesfully call the one parameter constructor passing items, you'd need something like
writeData data_writer(items);
Alternatively, you may want either member functions, or non-members. The choice would depend on whether you really want to model a class, which maintains certain invariants or not. An example of members,
class writeData
{
public:
void write_data() const;
void write_data(const vector<int> & DATAFILE) const;
void write_data(const vector<int> & DATAFILE, string) const;
};
Then
WriteData wd;
wd.write_data(items);
Example of non-members:
namespace writeData
{
void write_data();
void write_data(const vector<int> & DATAFILE);
void write_data(const vector<int> & DATAFILE, string);
};
Then
writeData::write_data(items);
Note I have made the vector<int> parameters const reference because they are not being moified in the functions.
My problem is in the following C++ code. On the line with the 'cout' I get the error:
"'number' was not declared in this scope".
.h
using namespace std;
class a{
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
int main(){
cout << "Your number is: " << number() << endl;
return 0;
}
number(){
int x = 1;
return x;
}
Note: I'm aware this isn't the cleanest code. I just wanted to get the function working and refresh my memory on how to use headers.
For minimal fix, three basic changes are necessary.
Proper implementation of the number() method
int a::number() {
int x = 1;
return x;
}
Proper invocation of the number() method
a aObject;
cout << "Your number is: " << aObject.number() << endl;
There are many other enhancements possible though.
Addition, as pointed out by #CPlusPlus, usable scope of number() method, for example declaring it public
class a{
public:
int number();
};
Try this in your cpp file
using namespace std;
#include <iostream>
#include "header.h"
void a::number()
{
int x = 1;
return x;
}
int main()
{
cout << "Your number is: " << a().number() << endl;
return 0;
}
As for your header file replace class with a struct. The reason you are getting this error is because the compiler cant find the variable number. It is actually a method of a class.The reason you are replacing the class with a struct is because by default everything in a struct is public. So your header file called header.h should look like this
using namespace std;
struct a
{
int number();
};
There are three issues with your code.
The definition of the function number().
As you declared, it is a member function of the class "a". In your .cpp, the class name should be used as a prefix to the function. I mean,
a::number(){
int x = 1;
return x;
}
As the function is a member of the class "a", there are only two ways of accessing it,
If the function is a static function in the class, you can access it with :: operator. Like a::number().
If the function is not a static function, that is true in your case, you should instantiate the object out of the class "a" and they use "." operator with the reference. I mean,
a obj;
obj.number().
Your function number() is declared in private scope. You may recall that by default the scope is a class is private unless you specify public or protected. So the private function number() cannot be used outside the declared class unless there is a friend to it.
Below the code that I fixed,
.h
using namespace std;
class a{
public:
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
a::number(){
int x = 1;
return x;
}
int main(){
a obj;
cout << "Your number is: " << obj.number() << endl;
return 0;
}