Declaration of Array of Pointers Not Being Recognized - c++

using namespace std;
namespace sdds {
const int MAX_NO_OF_ITEMS = 10;
class Menu {
char* m_title;
int indentation;
int m_numofItems;
//issue
MenuItem*m_items = new MenuItem[MAX_NO_OF_ITEMS + 1]; // Declaration of MenuItem type not working
public:
Menu();
Menu(const char* title, int indent = 0);
Menu(const Menu& menu);
~Menu();
bool isEmpty() const;
void add(const char* str);
int run();
ostream& display(ostream& os);
void display() const;
Menu& operator=(const Menu& menu);
operator bool();
operator int();
string& operator=(const char* str);
Menu& operator<<(const char* item);
//friend class MenuItem;
};
class MenuItem {
char* i_name;
//public:
MenuItem();
MenuItem(char*);
MenuItem(const MenuItem& mi);
void setMenuItem(char*);
~MenuItem();
//ostream& display(ostream& os);
ostream& operator<<(ostream& os) const;
istream& operator>>(istream& os) const;
MenuItem& operator=(const MenuItem& mi);
friend class Menu;
};
}
I am trying to make the Menu class hold an array of MenuItem pointers. Menu is a friend of MenuItem. I am having trouble trying to declare this array of pointers as I am receiving errors that tell me 'MenuItem' is not a type. "C4430 missing type specifier - int assumed." "C2143 syntax error: missing ';' before '*'"
and "C2238 unexpected token(s) preceding ';'"

Class MenuItem should be defined first in your case then. It is not known at the time of Declaration
using namespace std;
namespace sdds {
const int MAX_NO_OF_ITEMS = 10;
class Menu;
class MenuItem {
char* i_name;
//public:
MenuItem();
MenuItem(char*);
MenuItem(const MenuItem& mi);
void setMenuItem(char*);
~MenuItem();
//ostream& display(ostream& os);
ostream& operator<<(ostream& os) const;
istream& operator>>(istream& os) const;
MenuItem& operator=(const MenuItem& mi);
friend class Menu;
};
class Menu {
char* m_title;
int indentation;
int m_numofItems;
MenuItem*m_items = new MenuItem[MAX_NO_OF_ITEMS + 1];
public:
Menu();
Menu(const char* title, int indent = 0);
Menu(const Menu& menu);
~Menu();
bool isEmpty() const;
void add(const char* str);
int run();
ostream& display(ostream& os);
void display() const;
Menu& operator=(const Menu& menu);
operator bool();
operator int();
string& operator=(const char* str);
Menu& operator<<(const char* item);
};
}

Related

use std::for_each with bind a member function on a std::set , the code can't be compile

I can compile normal,when I use vector:
TEST(function_obj,bindMemeber1){
std::vector<Person> v {234,234,1241,1241,213,124,152,421};
std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) );
}
but when I use set,something wrong:
TEST(function_obj,bindMemeber1){
std::set<Person,PersonCriterion> v{234,234,1241,1241,213,124,152,421};
std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) );
}
clion's tips
The IDE tell me that something wrong.when I force IDE to compile, it also can't compile successfully .
Below is the code of Person;
class Person{
private:
size_t no;
std::string name;
public:
Person():no(0){};
Person(size_t n): no(n){};
Person(const Person& p):no(p.no),name(p.name){};
friend class PersonCriterion;
size_t getNo() const;
void print(){
std::cout<<no<<' ';
}
const std::string &getName() const;
};
class PersonCriterion{
public:
bool operator()(const Person& p1,const Person& p2){
return p1.no<=p2.no;
}
};
size_t Person::getNo() const {
return no;
}
const std::string &Person::getName() const {
return name;
}
Elements got from std::set are const-qualified; they're supposed to be non-modifiable. You should mark Person::print as const then it could be called on a const object.
class Person {
...
void print() const {
// ^^^^^
std::cout<<no<<' ';
}
...
};
BTW: Better to mark operator() in PersonCriterion as const too.
class PersonCriterion {
public:
bool operator()(const Person& p1, const Person& p2) const {
return p1.no<=p2.no;
}
};

Overloading ">>" for a template?

I'm trying to overload the ">>" operator so i can read and store a new Atlas<Animal *> from the keyboard.
The atlas template class has a list in which i'm storing pointers to each Animal object. Here is the code:
class Animal {
protected:
std::string m_name;
public:
Animal() {}
Animal (std::string name): m_name {name} {}
virtual void set_name(std::string name) {m_name = name;}
virtual std::string get_name () {return m_name;}
virtual std::string regn() const { return "???"; }
virtual ~Animal(){
cout << "Destructor animal"<<'\n';}
friend istream& operator >> (istream &in, Animal* k){
in>> k->m_name;
return in;}
}; //pointers to objects from this class will be stored in Atlas2;
//declaration for >> operator
template <class T>
class Atlas2;
template<typename T>
std::istream& operator>>(std::istream& in, const Atlas2<T>& A);
// Template class
template<class T>
class Atlas2{
public:
int nr_pesti;
int m_length;
std::list<T> pages;
Atlas2(){m_length = 0; nr_pesti = 0;}
~Atlas2(){}
void adauga(T data);
Atlas2 operator += (const T& data){
this->m_length++;
this->pages.push_back(data);
return *this;}
friend std::istream& operator>> <> (std::istream& in, const Atlas2<T>& A);
};
template <class T>
istream operator>> (istream &in, const Atlas2<T> &A)
{
in >> A.m_length;
for (int i=1; i<=A.m_length; i++){
T data = new T;
cin >> data;
A.pages.push_back(data);}
return in;
}
template <class T>
void Atlas2<T>::adauga(T data){m_length = m_length+1;
pages.push_back(data);}
// here's the main:
int main(){
Atlas2<Animal *> Atlas3;
cin >> Atlas3;
return 0;}
What am I doing wrong here? I get this error when compiling:
ambiguous overload for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Atlas2<Animal*>') at line 58 (Where i type cin>>Atlas3) and these Warnings for the >> operator in the template class : note: candidate: 'std::istream& operator>>(std::istream&, const Atlas2<T>&) [with T = Animal*; std::istream = std::basic_istream<char>]'

How to write/read classes within classes to binary file C++

I'm working on a project where I have to write a class that contains three other classes as private member variables to a binary file, where it can then be read back into variables to be used in the code. The code writes to the file, but I don't know if it is writing the correct info as when I try to read the file it reads in junk. I have included my current setup, does this look correct? If so, what could be going wrong, and if not, how can I fix this?
If you need me to add any extra code, please ask. Another consideration is that two of the classes being used as member functions for the players objects inherit from other classes.
if (cFile.is_open())
{
cFile.seekp(ios::beg);
for (int i = 0; i < 3; i++)
{
cFile.write(reinterpret_cast<char *>(&players[i]), sizeof(Character));
}
cFile.seekg(ios::beg);
for (int i = 0; i < 3; i++)
{
cFile.read(reinterpret_cast<char *>(&playersRead[i]), sizeof(Character));
playersRead[i].display();
}
cFile.close();
}
else
{
cout << "Error opening file." << endl;
}
I've been working on this code for a few days and am really having trouble. I appreciate any help I can get, thanks in advance.
#pragma once
#include <iostream>
using std::ostream;
#include "string.h"
#include "coinPouch.h"
#include "backpack.h"
class Character
{
public:
Character();
Character(String name);
Character(String name, CoinPouch wallet, Backpack storage);
Character(const Character & copy);
~Character();
Character & operator =(const Character & rhs);
friend ostream & operator << (ostream & out, const Character & c);
void purchase(int p, int g, int s, int c);
void income(int p, int g, int s, int c);
void addPotion(const Potion & toAdd);
void checkBalance();
void checkBackpack();
void changeName(const String & newN);
void display();
String getName();
CoinPouch getWallet();
Backpack getStorage();
void setName(String name);
void setWallet(CoinPouch wallet);
void setStorage(Backpack storage);
private:
String m_name;
CoinPouch m_wallet;
Backpack m_storage;
};
#include "character.h"
using std::endl;
using std::cout;
Character::Character() : m_name("Player")
{
CoinPouch initialW;
Backpack initialS;
m_wallet = initialW;
m_storage = initialS;
}
Character::Character(String name) : m_name(name)
{
CoinPouch initialW;
Backpack initialS;
m_wallet = initialW;
m_storage = initialS;
}
Character::Character(String name, CoinPouch wallet, Backpack storage) : m_name(name), m_wallet(wallet), m_storage(storage)
{
}
Character::Character(const Character & copy) : m_name(copy.m_name), m_wallet(copy.m_wallet), m_storage(copy.m_storage)
{
}
Character::~Character()
{
}
Character & Character::operator =(const Character & rhs)
{
if (this != &rhs)
{
m_name = rhs.m_name;
m_wallet = rhs.m_wallet;
m_storage = rhs.m_storage;
}
return *this;
}
ostream & operator << (ostream & out, const Character & c)
{
out << c.m_name << ": " << endl;
out << c.m_wallet << endl;
out << c.m_storage << endl;
return out;
}
void Character::purchase(int p, int g, int s, int c)
{
m_wallet.buy(p, g, s, c);
}
void Character::income(int p, int g, int s, int c)
{
m_wallet.add(p, g, s, c);
}
void Character::addPotion(const Potion & toAdd)
{
m_storage.addPotion(toAdd);
}
void Character::checkBalance()
{
m_wallet.display();
}
void Character::checkBackpack()
{
m_storage.displayContents();
}
void Character::changeName(const String & newN)
{
m_name = newN;
}
void Character::display()
{
cout << m_name << ": " << endl;
m_wallet.display();
m_storage.displayContents();
}
String Character::getName()
{
return m_name;
}
CoinPouch Character::getWallet()
{
return m_wallet;
}
Backpack Character::getStorage()
{
return m_storage;
}
void Character::setName(String name)
{
m_name = name;
}
void Character::setWallet(CoinPouch wallet)
{
m_wallet = wallet;
}
void Character::setStorage(Backpack storage)
{
m_storage = storage;
}
#pragma once
#include <iostream>
using std::ostream;
#include "string.h"
class CoinPouch
{
public:
CoinPouch();
CoinPouch(String init);
CoinPouch(int p, int g, int s, int c);
CoinPouch(const CoinPouch & copy);
~CoinPouch();
CoinPouch & operator = (const CoinPouch & rhs);
friend ostream & operator << (ostream & out, const CoinPouch & c);
void add(int p, int g, int s, int c);
bool checkCost(int p, int g, int s, int c);
void buy(int p, int g, int s, int c);
void convertCost();
void roundUp();
void display();
int getP();
int getG();
int getS();
int getC();
private:
String m_amount;
int m_platinum;
int m_gold;
int m_silver;
int m_copper;
};
#pragma once
#include "potions.h"
class DynamicArray
{
public:
// Constructors
DynamicArray();
~DynamicArray();
DynamicArray(const DynamicArray & copy);
// Op Equals
DynamicArray & operator =(const DynamicArray & rhs);
// Insert, delete, and get elements functions
int getElements();
void Insert(const Potion & add);
void Delete(const Potion & rmv);
void display();
// Overloaded operators
Potion & operator [](int index);
friend ostream & operator << (ostream & out, const DynamicArray & d);
private:
// Member variables
Potion * m_array;
int m_elements;
// Find function
int Find(const Potion & target);
};
#pragma once
#include "string.h"
#include <iostream>
using std::ostream;
class Potion
{
public:
// Constructors
Potion();
Potion(String name, String description, String potency, String cost);
Potion & operator = (const Potion & rhs);
Potion(const Potion & copy);
// Desctructor
~Potion();
// Overloaded operators
bool operator == (const Potion & rhs) const;
friend ostream & operator << (ostream & out, const Potion & p);
// Getter functions
String getName();
String getDesc();
String getPotency();
String getCost();
int getP();
int getG();
int getS();
int getC();
// Setter functions
void setName(String name);
void setDesc(String desc);
void setPotency(String potency);
void setCost(String cost);
// Convert and display functions
void convertCost();
void display();
private:
// Strings to hold item information
String m_name;
String m_description;
String m_potency;
String m_cost;
// Ints to hold cost information
int m_platinum;
int m_gold;
int m_silver;
int m_copper;
// Logical test
bool m_isnull = false;
};
#pragma once
#include <iostream>
using std::ostream;
class String
{
public:
// Constructors
String();
String(char ch);
String(const char * str);
// Destructor
~String();
// Copy Constructor and Copy Assignment Constructor
String(const String & copy);
String & operator=(const String & rhs);
friend ostream & operator << (ostream & out, const String & s);
// Added Functionality
void display();
void upper();
void lower();
// Operator Conversion
operator char *();
operator const char *();
// Overloaded operator
bool operator == (const String & rhs) const;
private:
// Member variables
char * m_str;
int m_ischar;
};
#pragma once
#include "dynamicarray.h"
#include "coinPouch.h"
#include "string.h"
class Backpack
{
public:
Backpack();
Backpack(DynamicArray potions);
Backpack(const Backpack & copy);
~Backpack();
Backpack & operator = (const Backpack & rhs);
friend ostream & operator << (ostream & out, const Backpack & c);
void addPotion(const Potion & add);
void usePotion(const Potion & rm);
void displayContents();
private:
DynamicArray m_potions;
int m_number;
};
This is a school project, and I am supposed to write the Character class to a binary file in order to save the characters so I can load them in on the program start. Right now I'm just trying to make sure that they can be successfully written to and read from the binary file and I have had no luck.
My bad, didn't know what to post and I didn't want to post everything in my file. Here is the character class. Let me know what else is needed, if anything.
It should be immediately obvious that this code can't possibly work.
cFile.write(reinterpret_cast<char *>(&players[i]), sizeof(Character));
However big sizeof(Character) is, we could have a Character with an m_name that takes up more bytes than that. So this code can't possibly be writing the character's name, and it clearly needs to do that.
Before you write anything to a file, decide on (and ideally, document) a file format at the byte level. Make sure your code writes in the format you documented and also can read in the format you documented. Skipping this step leads to pain and it also makes debugging impossible because you can't look at the file and compare it to a specification to see whether the writer or the reader is at fault.
Had you documented what bytes the player's name will occupy in the file, you'd immediately realize that you either need to have a variable-length object and encode the length somehow or pick a largest size name and allocate those many bytes. But because you skipped that vital step, you never actually worked out how to write a Character to a file.

Crashing when trying to delete character array

When it gets to the delete portion where test2 needs to delete the String object it crashes. I am not sure why it crashes. It says "Debug Assertion failed!". Am I deleting the dynamically alloacted char array wrong?
strdrv.cpp:
#include <iostream>
#include <stdlib.h>
#include "strdrv.h"
int main() {
test2();
return 0;
}
void test2() {
cout << "2. Testing S2: String one arg (char *) constructor."
<< endl << endl;
csis << "2. Testing S2: String one arg (char *) constructor."
<< endl << endl;
String s2("ABC");
s2.print();
wait();
}
String.cpp:
#include "String.h"
#include <iostream>
using namespace std;
String::String(char* s) {
int sLength = 0;
for (int i = 0; s[i] != '\0'; i++) {
sLength++;
}
buf = new char[sLength+1];
dynamicallyAlloc = true;
buf = s;
length = sLength;
/*buf[length] = '\0';*/
}
String::~String() {
if(dynamicallyAlloc)
delete []buf;
}
String.h:
#ifndef _STRING_H
#define _STRING_H
#include <iostream>
using namespace std;
class String {
protected:
bool dynamicallyAlloc;
char nullChar;
int length;
char* buf;
void calculateStringLength();
public:
String();
String(char*);
String(char);
String(int);
String(const String&);
String(char, int);
~String();
int getLength() const;
char* getString() const;
String& operator=(const String&);
String& operator=(const char*);
String& operator+=(const String&);
String operator+() const;
char& operator[](int);
String& operator++();
String& operator--();
String operator++(int);
String operator--(int);
String substr(int, int);
void print();
friend String operator+(const String&, const String&);
friend String operator+(const String&, const char*);
friend String operator+(const char*, const String&);
friend String operator+(const String&, char);
friend String operator+(char, const String&);
friend char* operator+(const String&, int);
friend char* operator+(int, const String&);
friend int operator==(const String&, const String&);
friend int operator!=(const String&, const String&);
friend int operator<(const String&, const String&);
friend int operator<=(const String&, const String&);
friend int operator>(const String&, const String&);
friend int operator>=(const String&, const String&);
friend ostream& operator<<(ostream& os, const String& s1);
};
#endif
To copy the array contents, do not copy the pointer, Instead of
buf = s;
you want copy the contents
memcpy(buf,s, sLength+1);
This preserves the buf you have allocated for later deletion.

c++ error: qualifiers can only be specified

I am not completely sure why this is generating that error:
const class MyString {
public:
MyString() { _len = 0; _str = NULL; }
MyString(const char* in);
MyString(const MyString&);
~MyString();
int set(const char*);
int set(const MyString&);
int setLength(int len) { _len = len; return 0; }
int getLength() { return _len; }
char * getStr() { return _str; }
int getStr(char* out) const;
MyString operator+(const MyString & in);
MyString operator+(const char* in);
MyString operator+(const char in) {const char* temp = &in; return *this + temp; }
MyString operator=(const MyString & in)
{ this->set(in); return *this; }
MyString operator=(const char* in)
{ if(in) this->set(in); return *this; }
MyString operator=(const char in) {const char* temp = &in; return *this = temp; }
MyString operator+=(const MyString & in)
{ this->set(*this + in); return *this; }
MyString operator+=(const char* in)
{ if(in) this->set(*this + in); return *this; }
MyString operator+=(const char in) { return (*this + in); }
int operator==(const MyString& in);
int operator!=(const MyString& in);
int operator==(const char* in);
int operator!=(const char* in);
friend ostream& operator<<(ostream& os, const MyString & in)
{ os << in._str; return os; }
protected:
char * _str;
int _len;
};
The error is being generated at the last line. The only code before that definition are 'standard' #includes and using namespace std.
The error message you posted is not complete, but nevermind that.
Long story short: remove the const qualifier at the very top of your class declaration, the one just before the class keyword. You can only add cv-qualifiers (const / volatile) either on variables or methods.