How to combine array.h, array.cpp and main.cpp files together? - c++

How to combine array.h, array.cpp and main.cpp files together? I am getting an error while compiling main.cpp, that class Array is not declared in scope.
main.cpp:
#include<iostream>
#include "Array.h"
#include "Array.cpp"
using namespace std;
int main(){
Array a;
a.Array();
return EXIT_SUCCESS;
}
Array.h:
#ifndef ARRAY_H_INCLUDED
#define ARRAY_H_INCLUDED
class Array{
private:
int data;// The value or data stored in the node
int ArraySize;//Size of array
int* array;
public:
Array();
};
#endif
Array.cpp:
#include <iostream>
#include <cstdlib>
using namespace std;
#include "Array.h" // user defined header file
Array::Array(){ //initialise array
cout << "Initialising array elements----------------->"<< endl;
for (int i=0; i < 4; i++){
//array[i]= 1;
cout << i << endl;
}
}
ERROR message: invalid use of 'class Array'

The problem you have is that you are attempting to call the constructor of a class on an instance of that class:
Array a;
a.Array();
When you declare a function the same name as a class, you are creating a constructor for that class.
class Array
{
public:
// Default constructor
Array();
// This is a function you can call
void PrintData();
}
You can't call this function though. It's called automatically when you create an object of class Array:
Array a; // This will call Array's constructor
a.PrintData(); // This will call the function PrintData on the object 'a'

Related

Invalid use of non static data member C++

Here is my code
main.cpp
#include <iostream>
#include "header.h"
#include "source.cpp"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
int testarray[]={1,3,5,7};
mymatrix* first=new mymatrix(testarray,2,2);
return 0;
}
and header.h
using namespace std;
#include <iostream>
#include <string>
class mymatrix{
public:
int i;
int j;
int marray[];
mymatrix(int m[],int rows,int cols ) : marray(m),i(rows),j(cols)
{
cout<<"this is for testings ";
}
mymatrix()
{};
~mymatrix(){
// delete[] marray;
};
};
I get this error :Invalid use of non static data member mymatrix::i
what I wanna do is make a object of my
matrix class and pass an array
Convert it from
int marray[];
to
int *marray;
In addition, either use C paradigm or use C++ one but not the mixture.
Instead of
mymatrix* first=new mymatrix(testarray,2,2);
use
mymatrix first(testarray,2,2);
Let the compiler allocate and release the memory instead of you.
If you have no restriction about the C++ libraries that you use, consider std::vector library to manage your dynamic arrays.
Instad of managing memory out of the object, manage it inside the object specially inside constructor and destructor.

C++ Error: conversion to non-scalar type requested?

I'm fairly new to C++ and i'm trying to build a linked list with a container class called FlexString. In main() I want to instantiate the FlexString class by simply saying: "FlexString flex_str = new FlexString();" calling the constructor etc. But it won't compile, the error is at the bottom. Here is my code:
//FlexString.h file
#ifndef FLEXSTRING_CAMERON_H
#define FLEXSTRING_CAMERON_H
#include "LinkedList.h"
#include <string>
using namespace std;
using oreilly_A1::LinkedList;
namespace oreilly_A1 {
class FlexString {
public:
FlexString();
void store(std::string& s);
size_t length();
bool empty();
std::string value();
size_t count();
private:
LinkedList data_list;
};
}
#endif
Here is the .cpp file for the FlexString class:
#include "FlexString.h"
#include "LinkedList.h"
#include <string>
using namespace std;
namespace oreilly_A1 {
FlexString::FlexString() {
}
void FlexString::store(string& s) {
data_list.list_head_insert(s);
}
std::string value() {
data_list.list_getstring();
}
}
Here's the main program file.
#include <iostream>
#include <cstdlib>
#include "FlexString.h"
using namespace std;
using oreilly_A1::FlexString;
int main() {
FlexString flex_str = new FlexString();
cout << "Please enter a word: " << endl;
string new_string;
cin >> new_string;
flex_str.store(new_string);
cout << "The word you stored was: "+ flex_str.value() << endl;
}
error: conversion from 'oreilly_A1::FlexString*' to non-scalar type 'oreilly_A1::FlexString' requested. "FlexString flex_str = new FlexString();"
FlexString flex_str = new FlexString();
is wrong since the RHS of the assignment is a pointer to a FlexString while the LHS is an object.
You can use:
// Use the default constructor to construct an object using memory
// from the stack.
FlexString flex_str;
or
// Use the default constructor to construct an object using memory
// from the free store.
FlexString* flex_str = new FlexString();

Data "member not declared in this scope"

I'm trying to create a vector which will store objects. I have added to the header file of the class as a private data member.
I am trying to initialize this vector as being empty (so that I can add objects to it later on in the program) but when I compile this program to test, this error is returned:
...error: '_bookingVector' was not declared in this scope|
I think the problem is with my initialization list on my default constructor(_bookingVector is obviously the vector):
Schedule::Schedule() : _bookingVector()
{ }
Is my syntax wrong? Or are vectors initialized differently?
Here is my code:
Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include "Booking.h"
#include <vector>
using namespace std;
class Schedule
{
public:
Schedule();
void AddBooking(int bday, int btime, int btrainer, int bid);
void RemoveBooking(int bday, int btime);
void DisplaySchedule();
void DisplayAvailableTimeSlots();
//For Testing
void DisplayDebug();
private:
vector<Booking> _bookingVector;
};
#endif // SCHEDULE_H
Schedule.cpp
#include "Schedule.h"
#include "Booking.h"
#include <vector>
#include <iostream>
Schedule::Schedule() : _bookingVector()
{ }
void AddBooking(int bday, int btime, int btrainer, int bid){
Booking bookingObject(bday, btime, btrainer, bid);
_bookingVector.push_back(bookingObject);
}
void DisplayDebug(){
for(int i = 0; i < _bookingVector.size(); ++i){
cout << _bookingVecotr[i] << endl;
}
}
I'm very eager to learn what I'm doing wrong and fix it.
The issue is not with the constructor, which looks fine if unnecessary1. The issue is that you have defined AddBooking and DisplayDebug as non-member functions, but these should be members in order to access other members of the class.
Modify the definitions to be in the scope of the Schedule class thus:
void Schedule::AddBooking(int bday, int btime, int btrainer, int bid) { ...
^^^^^^^^^^
void Schedule::DisplayDebug(){ ...
^^^^^^^^^^
Also, don't say using namespace std in a header file (I'd go further and say don't say it anywhere but there isn't universal agreement on that.)
1 Your default constructor does not do anything that the compiler-generated one wouldn't do. You can safely remove it.

Why is my array undefined in main when the class headers are included?

So here is the main where i'm trying to call the array by a pointer:
#include <iostream>
#include "Lottery.h"
#include "Player.h"
#include "LotteryData.h"
using namespace std;
int main()
{
Player player;
Lottery random;
LotteryData data;
player.Input();
random.setRandomNumber();
data.PassInfo(int (&Numbers)[6][6]);
}
Apparently "Numbers" is undefined even though the header is included, here's the header and .cpp files relating to it.
LotteryData.h
#pragma once
#include <iostream>
#include <fstream>
#include "Lottery.h"
#include "Player.h"
using namespace std;
class LotteryData
{
private:
public:
LotteryData();
~LotteryData();
void PassInfo(int (&Numbers)[6][6]);
};
LotteryData.cpp
#include <iostream>
#include <fstream>
#include "LotteryData.h"
using namespace std;
LotteryData::LotteryData()
{
}
LotteryData::~LotteryData()
{
}
void LotteryData::PassInfo(int (&Numbers)[6][6])
{
int* ptr;
FILE *Numfile;
Numfile = fopen("C:/Num.txt", "wb");
ptr = &Numbers[6][6];
for (int i=0; i<36; i++)
{
fwrite(ptr, sizeof(int), 36*36, Numfile);
}
fclose(Numfile);
//ofstream out("Numbers.txt");
}
Everything seems fine, I'm puzzled why the reference in the main says the array is undefined, any ideas?
edit: Apologies, missed some bits
Player.h
#pragma once
#include <iostream>
#include <fstream>
using namespace std;
class Player
{
private:
public:
Player();
~Player();
void Input();
int Numbers[6][6];
};
Player.cpp
#include <iostream>
#include <fstream>
#include "Player.h"
using namespace std;
Player::Player()
{
}
Player::~Player()
{
}
void Player::Input()
{
int num(0);
int duplicate = 0;
int game = 0;
int NumberofGames = 0;
cout<<"How many games do you want to play for this weeks draw?"<<endl;
cin>>NumberofGames;
if (NumberofGames>6)
{
cout<<"Please enter an amount between 1 and 6"<<endl;
cin>>NumberofGames;
}
do
{
for (int i=0;i<6;i++)
{
cout<<"Enter Number "<< (i+1) <<endl;
cin>>num;
if (num > 0 && num <67)
{
Numbers[game][i]= num;
}
else
{
cout <<"Please enter number between 1 and 66"<<endl;
i = i-1;
}
}
game = game + 1;
NumberofGames = NumberofGames - 1;
}
while (NumberofGames=0);
}
void PassInfo(int (&Numbers)[6][6]);
That line does not declare an array - it declares a function. You have no declaration for an array in your class (in fact, you have no data members declared in your class at all).
If you want to declare a member array, you need to modify your class definition:
class LotteryData
{
private:
int Numbers[6][6]; // this declares an array
public:
LotteryData();
~LotteryData();
void PassInfo(int (&arr)[6][6]); // this is still a function declaration
};
Just because you made a function's parameter be named Numbers doesn't magically mean that your program has an array called Numbers declared in it.
So a Player has an array called "Numbers".
Then you would use it like this:
data.PassInfo(player.Numbers);
In your main() function,
data.PassInfo(int (&Numbers)[6][6]);
This is wrong. You should simply pass a reference to 2D array.
int (&Numbers)[6][6];
data.PassInfo(Numbers);

C++ Forward declaration and destructor

Two of my classes had to include each other. I made forward declarations instead, compilation is ok. One function of these classes is to call the destructor of the other. And that the compiler spits warnings at me, the destructor will not be called. What can I do? I can avoid this problem by creating another class for the function I need, avoiding the forward declarations but that would not be educative for me...
Here is my first class Header.h :
#ifndef H_HEADER
#define H_HEADER
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include "DataFiles.h"
class Character; // forward declaration Header <-> Character
class Header {
private:
Character * ch;
};
void cleanUp(std::vector <SDL_Surface*> & Vsurface, std::vector <TTF_Font*> & Vfont, std::vector <Character*> & Vchar);
// ... Other functions use in main.cpp
#endif
HEre is the Header.cpp:
#include "Header.h"
using namespace std;
void cleanUp(vector <SDL_Surface*> & Vsurface, vector <TTF_Font*> & Vfont, vector <Character*> & Vchar) {
for(unsigned int i(0); i < Vsurface.size(); i++)
SDL_FreeSurface(Vsurface[i]);
for(unsigned int i(0); i < Vfont.size(); i++)
TTF_CloseFont(Vfont[i]);
for(unsigned int i(0); i < Vchar.size(); i++)
delete Vchar[i];
TTF_Quit();
SDL_Quit();
}
And here is the other Character.h class:
#ifndef H_CHARACTER
#define H_CHARACTER
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include </usr/include/SDL/SDL_image.h>
#include </usr/include/SDL/SDL.h>
#include </usr/include/SDL/SDL_ttf.h>
#include "DataFiles.h"
#include "CharFrame.h"
class Header; // Forward declaration Header <-> Character
class Character {
public:
Character(std::string& dataPath);
~Character();
// .. other functions
private:
Header * h;
// ... other attributes
};
#endif
And here is my Character destructor:
Character::~Character() {
cout << "Character " << m_name << " deleted.\n-----------------------------------\n" << endl;
}
So when my program ends, I call upon the Header's function "cleanUp()" giving it a vector of pointers to Characters. Every pointer should then be deleted through the Character's destructor ~Character();
However compilation gives me three warnings:
Header.cpp: In function ‘void cleanUp(std::vector<SDL_Surface*>&, std::vector<_TTF_Font*>&, std::vector<Character*>&)’:
Header.cpp:66:17: warning: possible problem detected in invocation of delete operator: [enabled by default]
Header.cpp:66:17: warning: invalid use of incomplete type ‘struct Character’ [enabled by default]
Header.h:27:7: warning: forward declaration of ‘struct Character’ [enabled by default]
Header.cpp:66:17: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined
And once my program terminates, the character's destructor's message won't show up which means the destructor clearly isn't called.
What am I doing wrong with the forward declarations?
Yep, that's what the (draft) standard says (§5.3.5.5);
If the object being deleted has incomplete class type at the point of deletion and the complete class has a
non-trivial destructor or a deallocation function, the behavior is undefined.
(a non trivial destructor being one you defined yourself)
To fix it, just #include "Character.h" in header.cpp before invoking delete to allow the type to be completely declared.
When you use class MyClass; to forward declare your class, this only declares that the thing with the name MyClass is a class, it does not declare the internal methods of the class.
Whenever you need to use one of the internal methods (such as a non-trivial destructor) you need to include the full declaration of the class (this means include the header file containing the class definition). Without this, the compiler has no way of knowing what the internal structure of your class actually looks like.
Here is an example:
// main.cpp
#include "head1.hpp" // An instance of Head1 is created in this file
#include "head2.hpp" // An instance of Head2 is created in this file
int main(int argc, char** argv)
{
Head1 head1(true);
Head2 head2(true);
return 0;
}
// head1.hpp
#ifndef HEAD1_HPP
#define HEAD1_HPP
class Head2; // A pointer to a class is declared, but no instance is created
// so here we only need a forward declaration
class Head1
{
public:
Head1(bool real=false);
~Head1();
private:
Head2* myHead2;
};
#endif /* #ifndef HEAD1_HPP */
// head2.hpp
#ifndef HEAD2_HPP
#define HEAD2_HPP
class Head1; // Same as above
class Head2
{
public:
Head2(bool real=false);
~Head2();
private:
Head1* myHead1;
};
#endif /* #ifndef HEAD2_HPP */
// head1.cpp
#include "head1.hpp" // Include the header we are defining methods for
#include "head2.hpp" // We also create an instance of Head2 in here
#include <iostream>
using namespace std;
Head1::Head1(bool real) {
myHead2 = real ? new Head2() : NULL;
cout << "Hello Head 1" << endl;
}
Head1::~Head1() {
cout << "Bye Head 1" << endl;
if (myHead2 != NULL) delete myHead2;
}
// head2.cpp
#include "head2.hpp" // As above
#include "head1.hpp"
#include <iostream>
using namespace std;
Head2::Head2(bool real) {
myHead1 = real ? new Head1() : NULL;
cout << "Hello Head 2" << endl;
}
Head2::~Head2() {
cout << "Bye Head 2" << endl;
if (myHead1 != NULL) delete myHead1;
}