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;
}
Related
I am just learning about classes in C++, and I am trying to create this Coin class that simulates a coin flip with a method called toss() that will return either 0 or 1 which represent heads or tails respectively.
#include <iostream>
#include <cstdlib>
using namespace std;
class Coin {
private:
public:
Coin();
int toss();
};
Coin::Coin();
int Coin::toss() {
int num;
num = rand() % 2;
return num;
}
int main() {
Coin C;
cout << C.toss() << endl;
}
I keep getting an error that says: error: declaration of 'Coin::Coin()' outside of class is not definition. I am assuming that I did not declare my constructor correctly, but I am not sure.
The problem is that you're trying to declare the constructor outside the class when you wrote Coin::Coin();.
To solve this replace Coin::Coin(); with Coin::Coin(){} as shown below:
class Coin {
private:
public:
Coin();
int toss();
};
//----------v--->semicolon removed from here
Coin::Coin() //this is a definition now
{
}
I am learning classes and OOP, so I was doing some practice programs, when I came across the weirdest bug ever while programming.
So, I have the following files, beginning by my class "pessoa", located in pessoa.h:
#pragma once
#include <string>
#include <iostream>
using namespace std;
class pessoa {
public:
//constructor (nome do aluno, data de nascimento)
pessoa(string newname="asffaf", unsigned int newdate=1996): name(newname), DataN(newdate){};
void SetName(string a); //set name
void SetBornDate(unsigned int ); //nascimento
string GetName(); //get name
unsigned int GetBornDate();
virtual void Print(){}; // print
private:
string name; //nome
unsigned int DataN; //data de nascimento
};
Whose functions are defined in pessoa.cpp
#include "pessoa.h"
string pessoa::GetName ()
{
return name;
}
void pessoa::SetName(string a)
{
name = a;
}
unsigned int pessoa::GetBornDate()
{
return DataN;
}
void pessoa::SetBornDate(unsigned int n)
{
DataN=n;
}
A function, DoArray, declared in DoArray.h, and defined in the file DoArray.cpp:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
pessoa** pointer= &p;
return pointer;
}
And the main file:
#include <string>
#include <iostream>
#include "pessoa.h"
#include "DoArray.h"
#include <cstdio>
using namespace std;
int main()
{
//pessoa P[10];
//cout << P[5].GetBornDate();
pessoa** a=DoArray(5);
cerr << endl << a[0][3].GetBornDate() << endl;
cerr << endl << a[0][3].GetName() << endl;
return 0;
}
The weird find is, if I comment one of the methods above, "GetBornDate" or GetName, and run, the non-commented method will run fine and as supposed. However, if both are not commented, then the first will run and the program will crash before the 2nd method.
Sorry for the long post.
Let's look into this function:
int *get()
{
int i = 0;
return &i;
}
what is the problem with it? It is returning pointer to a local variable, which does not exist anymore when function get() terminates ie it returns dangling pointer. Now your code:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
return &p;
}
do you see the problem?
To clarify even more:
typedef pessoa * pessoa_ptr;
pessoa_ptr* DoArray(int n)
{
pessoa_ptr p= whatever;
return &p;
}
you need to understand that whatever you assign to p does not change lifetime of p itself. Pointer is the same variable as others.
I hope this is not a stupid question. Basically I would like to access a string stored in a Class (Statement is the name I am using) in a vector of type Statement. Basically I am trying to store objects in a dynamic hierarchy of objects.
Types.cpp:
#include<iostream>
#include<fstream>
#include <string>
#include <vector>
using namespace std;
class Statement{
public:
vector<string> Inner_String;
vector<Statement> Inner_Statement;
string contents;
void set_contents (string);
string get_contents(){ return contents;}
void new_string(string);
string get_string(int v){return Inner_String[v];}
void new_Inner_Statement(Statement);
Statement get_Inner_Statement(int v){return Inner_Statement[v];}
};
void Statement::set_contents(string s){
contents = s;
}
void Statement::new_string(string s){
Inner_String.push_back(s);
}
void Statement::new_Inner_Statement(Statement s){
Inner_Statement.push_back(s);
}
Main method:
#include <iostream>
#include "FileIO.h"
#include "Types.h"
using namespace std;
int main()
{
Statement test;
test.new_Inner_Statement(Statement());
Statement a = test.get_Inner_Statement(0);
a.set_contents("words");
cout << a.get_contents();
test.get_Inner_Statement(0).set_contents("string");
cout << test.get_Inner_Statement(0).get_contents();
return 0;
}
What happens is
cout << a.get_contents()
returns its string while
cout << test.get_Inner_Statement(0).get_contents()
does not.
Look at this piece of code:
test.get_Inner_Statement(0).set_contents("string");
^^^^^^^^^^^^^^^^^^^^^^^^^^^
It calls this function:
Statement get_Inner_Statement(int v)
which returns a copy object (temporary) of type statement. On this object, you calls set_contents function, at which cease to exists at the end of the call.
Then, you call:
test.get_Inner_Statement(0).get_contents();
that creates a new temporary, from the unchanged statement, and try to get its contents.
Hey guys I'm working on a project and I was doing pretty well until I hit this wall..
I am getting two errors:
error: 'binarySearch' was not declared in this scope
error: 'addInOrder' was not declared in this scope
Here are my files, I've tried quite a few things with no avail. Help would be much appreciated.
histogram.cpp
#include "histogram.h"
#include "countedLocs.h"
//#include "vectorUtils.h"
#include <string>
#include <vector>
using namespace std;
void histogram (istream& input, ostream& output)
{
// Step 1 - set up the data
vector<CountedLocations> countedLocs;
// Step 2 - read and count the requested locators
string logEntry;
getline (input, logEntry);
while (input)
{
string request = extractTheRequest(logEntry);
if (isAGet(request))
{
string locator = extractLocator(request);
int position = binarySearch (countedLocs,
CountedLocations(locator, 0));
/** Hint - when looking CountedLocations up in any kind
of container, we really don't care if the counts match up
or not, just so long as the URLs are the same. ***/
if (position >= 0)
{
// We found this locator already in the array.
// Increment its count
++countedLocs[position].count;
}
else
{
// This is a new locator. Add it.
CountedLocations newLocation (locator, 1);
addInOrder (countedLocs, newLocation);
}
}
getline (input, logEntry);
}
// Step 3 - write the output report
for (int i = 0; i < countedLocs.size(); ++i)
output << countedLocs[i] << endl;
}
countedLocs.cpp
#include "countedLocs.h"
#include <iostream>
#include <vector>
using namespace std;
int CountedLocations::binarySearch(const vector<CountedLocations> list, CountedLocations searchItem)
{
//Code was here
}
int CountedLocations::addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value)
{
//Code was here
}
countedLocs.h
#ifndef COUNTEDLOCATIONS
#define COUNTEDLOCATIONS
#include <iostream>
#include <string>
#include <vector>
struct CountedLocations
{
std::string url;
int count;
CountedLocations (){
url = "";
count = 0;
}
CountedLocations(std::string a, int b){
url = a;
count = b;
}
int addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value);
int binarySearch (const std::vector<CountedLocations> list, CountedLocations searchItem);
};
inline
std::ostream& operator<< (std::ostream &out, CountedLocations& cL)
{
//out << "URL: " << cL.url << " count: " << cL.count << std::endl;
out << "\"" << cL.url << "\"," << cL.count;
return out;
}
#endif
The methods are member methods of CountedLocations... use something.extractLocator and something.binarySearch or make the histogram() to be also a member method of CountedLocations... (something is of type CountedLocations highly possibly will be countedLocs[position])
You have a free function histogram in which you are trying to use two member functions, addInOrder and binarySearch. In order to use them, you need to have an instance of CountedLocations.
If these are some kind of helper functions, which do not depend on the actual CountedLocations instance, I would turn them into static functions like this (you only need to change the header):
static int addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value);
And then you can call this function by specifying the type of your class:
CountedLocations::addInOrder(...);
You are trying to call member methods of a struct without an object of that type. Strange.
You need to look at what a namespace is.
You declare a class CountedLocations, so far so good. But then you try to use the member functions outside the CountedLocations namespace which will obviously never work.
int position = binarySearch (countedLocs,
CountedLocations(locator, 0));
binarySearch is a member function of the CountedLocations namespace. If you want to call that function you have to create an object that contains a reference to that member function.
CountedLocation myObject;
int position = myObject.binarySearch (countedLocs, CountedLocations(locator, 0));
I dont know if that solves your problem, but you should know this before you even attempt to solve a problem.
I'm working on a homework assignment for my C++ class and have ran across a problem that I cannot figure out what I am doing wrong.
Just to note, the separation of the files is necessary and I realize this would be much easier if I just made a structure AttackStyles inside the main and forgo the additional class file altogether.
The base of my problem is that I cannot seem to be able to loop through an array of classes and pull out base data. Here is the code:
// AttackStyles.h
#ifndef ATTACKSTYLES_H
#define ATTACKSTYLES_H
#include <iostream>
#include <string>
using namespace std;
class AttackStyles
{
private:
int styleId;
string styleName;
public:
// Constructors
AttackStyles(); // default
AttackStyles(int, string);
// Destructor
~AttackStyles();
// Mutators
void setStyleId(int);
void setStyleName(string);
// Accessors
int getStyleId();
string getStyleName();
// Functions
};
#endif
/////////////////////////////////////////////////////////
// AttackStyles.cpp
#include <iostream>
#include <string>
#include "AttackStyles.h"
using namespace std;
// Default Constructor
AttackStyles::AttackStyles()
{}
// Overloaded Constructor
AttackStyles::AttackStyles(int i, string n)
{
setStyleId(i);
setStyleName(n);
}
// Destructor
AttackStyles::~AttackStyles()
{}
// Mutator
void AttackStyles::setStyleId(int i)
{
styleId = i;
}
void AttackStyles::setStyleName(string n)
{
styleName = n;
}
// Accessors
int AttackStyles::getStyleId()
{
return styleId;
}
string AttackStyles::getStyleName()
{
return styleName;
}
//////////////////////////////////////////////
// main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "attackStyles.h"
using namespace std;
int main()
{
const int STYLE_COUNT = 3;
AttackStyles asa[STYLE_COUNT] = {AttackStyles(1, "First"),
AttackStyles(2, "Second"),
AttackStyles(3, "Third")};
// Pointer for the array
AttackStyles *ptrAsa = asa;
for (int i = 0; i <= 2; i++)
{
cout << "Style Id:\t" << ptrAsa->getStyleId << endl;
cout << "Style Name:\t" << ptrAsa->getStyleName << endl;
ptrAsa++;
}
system("PAUSE");
return EXIT_SUCCESS;
}
My question is why do I get the error:
"a pointer to a bound function may only be used to call the function"
on both ptrAsa->getStyleId and ptrAsa->getStyleName?
I cannot figure out what is wrong with this!
You are missing () around the function calls. It should be ptrAsa->getStyleId().
You are missing parenthesis on both calls, it should be
ptrAsa->getStyleId()
to call the function.
ptrAsa->getStyleId
is used to refer to a member value / attribute.
You need to invoke the function, not merely reference it:
std::cout << "Style Id:\t" << ptrAsa->getStyleId() << "\n";
std::cout << "Style Name:\t" << ptrAsa->getStyleName() << "\n";
You are Forgot to put () in last in Your Function(ptrAsa->getStyleId ) Calling with arrow operator.