I am beginner c++ programmer, It's my first program even (For those who are very keen to give negatives). I had written the same code in c but now trying to do in c++.
Where I get the following error.
error: ‘length’ was not declared in this scope
My code is as below.
#include <iostream>
#include <fstream>
#include <assert.h>
using namespace std;
class Huffman
{
public:
int data_size, length; //THis length variable is not accessible in main function below in main function.
Huffman(char *filename);
~Huffman();
struct Huffman1
{
int value;
unsigned char sym; /* symbol */
struct Huffman1 *left,*right; /* left and right subtrees */
}; typedef struct Huffman1 Node;
};
Huffman::Huffman(char * file_name)
{
//I will do something here soon
}
Huffman::~Huffman()
{
}
int main(int argc, char * * argv)
{
length=10; //Not accessible here.
if (argc < 2)
{
cout<<"Ohh.. Sorry , you forgot to provide the Input File please" <<endl;
return(0);
}
Huffman Object1(argv[1]);
return(0);
}
I am not sure that it's c++ programming error because it may be because i am compiling it g++ Filename.c -o filename. Could someone please correct if it's a programming error or it's due to the way i compile ?
thanks.
length is a member of the class, so it does not exist outside the class.
You can access lenth after creating an object of class Huffman as follows
Huffman Object(argv[1]);
Object.length = 10;
length belongs to Huffman class. So you should use it for Object1 after it's definition:
Huffman Object1(argv[1]);
Object1.length = 10;
You know, public: doesn't mean that anything put inside under that branch in the class tree, will be accessible everywhere it just means that you access the instance variables of the class through "dot notation" like so Object.length.
However if you truly wanted length to be accessible everywhere, you should declare it as a global variable:
short int length;
class Huffman{
...
};
...
It's a compile error and your code is responsible. You defined length inside your Huffman class. It's a member of that class, not a global variable.
Imagine your class as a C Struct. You'd need to create a struct first in order to access the variable. Same thing applies to C++ classes.
Try Object1.length = 10; after you create the instance of your class.
EDIT
For your purposes, use C++ classes as you would use C structs. That will do the trick.
I would actually put the Node struct declaration outside of the Huffman class. I think it's easier to understand. Also, using a typedef to a struct is not really that useful in C++ for these cases, the name of the struct is usable by just declaring the struct.
The pointers do not allocate memory for the struct themselves. Only after you allocate memory they will be usable, and even then they're members of Object1, so you need that too.
#include <iostream>
#include <fstream>
#include <assert.h>
using namespace std;
struct Node
{
int value;
unsigned char sym; /* symbol */
};
class Huffman
{
public:
int data_size, length; //THis length variable is not accessible in main function below in main function.
Huffman(char *filename);
~Huffman();
Node *left,*right; /* left and right subtrees */
};
Huffman::Huffman(char * file_name)
{
//I will do something here soon
}
Huffman::~Huffman()
{
}
int main(int argc, char * * argv)
{
length=10; //Not accessible here.
if (argc < 2)
{
cout<<"Ohh.. Sorry , you forgot to provide the Input File please" <<endl;
return(0);
}
Huffman Object1(argv[1]);
Object1.left = new Node;
Object1.right = new Node;
//Do your stuff here...
Object1.left->sym;
return(0);
}
This should get you started, it is by no means a perfect implementation. It's not even very C++ oriented, but I already went ahead of myself with the answer. This is a topic for a very different question, which you're welcome to ask in SO, but try not to make questions inside questions.
Good luck!
length is part of your class, not main, thus the compiler is right.
Members belong to an object and are accessed liek this:
Huffman huffmannObj(...);
std::cout << huffmannObj.length << std::endl;
length is a publicly accessible member of your class, but you'll need an instance of that class first before you can do anything with the member
Huffman h(whatever_constructor_params);
h.length = 10;
...is ok
Related
I am not sure why my function is not working. It should be printing out something out (an error message after the user goes out of bounds)I have set the array index at 3 index slots. I'm also getting an error "unused variable 'yourArray' I am not sure where to go from here. Still trying to learn c++ so and advice or help will be greatly appreciated.
#include <iostream>
using namespace std;
class safeArray{
public:
void outofBounds(int,int);
int yourArray[3];
int i;
};
void outofBounds(int,int);
int yourArray[3];
int i;
void outofBounds(int yourArray[],int sizeofArray) {
for (i=0;i<sizeofArray;i++){
cout<<"Please enter integer";
cin >>yourArray[i];
yourArray[i]++;
for (i=0;i>sizeofArray;){
cout<<"safeArray yourArray (" <<yourArray[0]<<","<<yourArray[3]<<")"
<<endl;
}}}
int main() {
void outofBounds(int,int);
int yourArray[3]; //Error: Used variable "yourArray"
};
Your Program is running fine. Unless you added the "-Werror" flag to the compiler, which would treat the "unused variable"-Warning as an Error.
The code compiles fine as seen on here: http://coliru.stacked-crooked.com/a/d648b94f205b51dc
Though your Program does not do what you want it to do, because of the following reasons:
1.) You have 3 redefinitions of outofBounds inside different namespaces:
one inside the classes namespace SafeArray which is a member function
of it
then inside the global space
and then inside the main-function (the entry point)
But the one being actually defined is the one in the global space (2nd one)
2.) You are not passing anything to the function inside main.
define your Array there first then call the function by doing:
int yourArray[3];
outofBounds(yourArray, 3);
3.) You probably wanted to define the member method "outofBounds" inside SafeArray-class. This can be done by writing the scope operator:: which specifies the class to which the member function belongs to:
class SafeArray { // is a class, can also be struct since everything is public anyways
public:
void outofBounds(int,int); // a member of the class SafeArray
// private:
int yourArray[3];
int i;
};
void SafeArray::outofBounds(int yourArray[],int sizeofArray) {
// do something...
}
but then again you need some constructor that initializes the members of your class. Some work needs to be done to make it work, like you want. Good Luck :)
I want to implement a function that can print out the value of one member variable (for example, 'aa') of struct ('Data') by it's name.
I try to use the macro definition as follows, but failed.
Is there a simple way to implement it?
#include <string>
#include <iostream>
using namespace std;
struct Data
{
int aa;
int bb;
int cc;
Data(): aa(1),bb(2),cc(3) {};
};
#define Param(a,b) a.##b
void Process(Data& data, const string& name)
{
cout << Param(data, name) << endl;
}
void main()
{
Data data;
Process(data, "aa");//I want print the value of Data.aa
Process(data, "bb");//I want print the value of Data.bb
Process(data, "cc");//I want print the value of Data.cc
}
This is not possible in C++.
This kind of usage is generally seen in scripting languages.
In C++ the variable names are constructed at compile time.
Your original code sample makes no sense to me because if you call Param(name) then the compiler has to know what instance of Data it has to use to determine the value of the member variable you want to get the value of (but I'm neither an expert using macros nor do I like them very much).
I tried to solve your problem using the following approach:
struct Data
{
int aa;
};
#define GetMemberValue(d, n) d.##n
int main()
{
Data d;
d.aa = 3;
int i = GetMemberValue(d, aa);
}
At least this approach returns the right result in this case.
Another thing is that you stated that you cannot call the member variables directly i.e. data.aa so you might run into the same issue using the macro. It's just a guess as I don't know the original code you're using.
I created a double linked list structure, and I want to use function duplaLista to connect nodes and insert values.I have actually found in someone elses question how to give struct as a parameter in function call. But it wont work for me(Incomplete type is not allowed). I also have read answers on that issue but I cant understand what am I doing wrong because I just saw it should be done that way not that I understood it completely? Can someone tell me what is wrong, and explain me why?
#include "DoubleList.h"
#include<iostream>
#include<stdio.h>
#include"string"
using namespace std;
struct Cvor
{
Cvor *head;
Cvor *tail;
char vred;
Cvor(const char &value, Cvor *prev = NULL, Cvor *next = NULL) : vred(value),
head(next), tail(prev)
{}
};
void duplaLista(Cvor *cvor)
{
}
int main(int argc, char *argv[])
{
Cvor cvor;
duplaLista(cvor);
return 0;
}
void duplaLista(Cvor *cvor)
A compiler reads the program to compile from the beginning to the end. At this point, Cvor is not defined. Your definition of this class appears later.
In C++, classes, templates, functions, and everything else must be defined before they are used.
You need to move the definition of the class out of the main() function and into the global scope, before it is used here.
You have two errors here. First, as you did not define a default constructor for Cvor, unless you provide the minimum essential parameters to construct Cvor, the declaration in main(i.e. Cvor cvor) will fail. You need to give it some sample const char & to be able to construct it. When that's done, you need to fix the incorrect type of parameter you provide to duplaLista. When corrected, your main function should look as follows. The parameter 'A' I gave below is just a sample initial value. Replace it with whatever you think is useful.
int main(int argc, char *argv[])
{
Cvor cvor('A');
duplaLista(&cvor);
return 0;
}
I need to create and use vector with structs of other class.
So class Scanner contains following struct structure:
class Scanner
{
struct structOneScan
{
unsigned int X_MULTIPLE_POS[290];
unsigned int Z_MULTIPLE_POS[290];
unsigned int I_MULTIPLE_COUNT[290];
}
structOneScan SnapsArray[3000] ;
};
in Draw.cpp i manipulate this struct:
if (Counter<3000)
{
for(int i = 0; i < 290; i++)
{
Scanner.SnapsArray[Counter].X_MULTIPLE_POS[i] = (double) (Scanner.X_POS[i] * X_Factor);
Counter ++;
};
Now that i have the information copied in my SnapsArray, i need to analyse this information and save it in a vector, cause there can be many such Scans.
Thats why i create another class CMeasurementResult, to save the structs in a vector:
#include "CScanner.h"
#include <vector>
using namespace std;
class CMeasureResult
{
public:
vector<structOneScan*>Scans;
};
but the way i try it doesn´t work. Also tried it over a Pointer from Scanner, but it doesn´t work too.
vectorScans; doesn´t work too.
vectorScans; ist the declaration. Qualifier 'scanner' is not a name of a class or namespace. Tempaltespecification out of 'vector<_Ty,_Ax>' can´t be generated. Sorry for bad translation, my compiler is in German language. So if I compile, this ist the Error. C++ Builder Embarcadero
I'm trying to implement a minheap in C++. However the following code keeps eliciting errors such as :
heap.cpp:24:4: error: cannot convert 'complex int' to 'int' in assignment
l=2i;
^
heap.cpp:25:4: error: cannot convert 'complex int' to 'int' in assignment
r=2i+1;
^
heap.cpp: In member function 'int Heap::main()':
heap.cpp:47:16: error: no matching function for call to 'Heap::heapify(int [11], int&)'
heapify(a,i);
^
heap.cpp:47:16: note: candidate is:
heap.cpp:21:5: note: int Heap::heapify(int)
int heapify(int i) //i is the parent index, a[] is the heap array
^
heap.cpp:21:5: note: candidate expects 1 argument, 2 provided
make: * [heap] Error 1
#include <iostream>
using namespace std;
#define HEAPSIZE 10
class Heap
{
int a[HEAPSIZE+1];
Heap()
{
for (j=1;j<(HEAPISZE+1);j++)
{
cin>>a[j];
cout<<"\n";
}
}
int heapify(int i) //i is the parent index, a[] is the heap array
{
int l,r,smallest,temp;
l=2i;
r=2i+1;
if (l<11 && a[l]<a[i])
smallest=l;
else
smallest=i;
if (r<11 && a[r]<a[smallest])
smallest=r;
if (smallest != i)
{
temp = a[smallest];
a[smallest] = a[i];
a[i]=temp;
heapify(smallest);
}
}
int main()
{
int i;
for (i=1;i<=HEAPSIZE;i++)
{
heapify(a,i);
}
}
}
Ultimately, the problem with this code is that it was written by someone who skipped chapters 1, 2 and 3 of "C++ for Beginners". Lets start with some basics.
#include <iostream>
using namespace std;
#define HEAPSIZE 10
Here, we have included the C++ header for I/O (input output). A fine start. Then, we have issued a directive that says "Put everything that is in namespace std into the global namespace". This saves you some typing, but means that all of the thousands of things that were carefully compartmentalized into std:: can now conflict with names you want to use in your code. This is A Bad Thing(TM). Try to avoid doing it.
Then we went ahead and used a C-ism, a #define. There are times when you'll still need to do this in C++, but it's better to avoid it. We'll come back to this.
The next problem, at least in the code you posted, is a misunderstanding of the C++ class.
The 'C' language that C++ is based on has the concept of a struct for describing a collection of data items.
struct
{
int id;
char name[64];
double wage;
};
It's important to notice the syntax - the trailing ';'. This is because you can describe a struct and declare variables of it's type at the same time.
struct { int id; char name[64]; } earner, manager, ceo;
This declares a struct, which has no type name, and variables earner, manager and ceo of that type. The semicolon tells the compiler when we're done with this statement. Learning when you need a semicolon after a '}' takes a little while; usually you don't, but in struct/class definition you do.
C++ added lots of things to C, but one common misunderstanding is that struct and class are somehow radically different.
C++ originally extended the struct concept by allowing you to describe functions in the context of the struct and by allowing you to describe members/functions as private, protected or public, and allowing inheritance.
When you declare a struct, it defaults to public. A class is nothing more than a struct which starts out `private.
struct
{
int id;
char name[64];
double wage;
};
class
{
public:
int id;
char name[64];
double wage;
};
The resulting definitions are both identical.
Your code does not have an access specifier, so everything in your Heap class is private. The first and most problematic issue this causes is: Nobody can call ANY of your functions, because they are private, they can only be called from other class members. That includes the constructor.
class Foo { Foo () {} };
int main()
{
Foo f;
return 0;
}
The above code will fail to compile, because main is not a member of Foo and thus cannot call anything private.
This brings us to another problem. In your code, as posted, main is a member of Foo. The entry point of a C++ program is main, not Foo::main or std::main or Foo::bar::herp::main. Just, good old int main(int argc, const char* argv[]) or int main().
In C, with structs, because C doesn't have member functions, you would never be in a case where you were using struct-members directly without prefixing that with a pointer or member reference, e.g. foo.id or ptr->wage. In C++, in a member function, member variables can be referenced just like local function variables or parameters. This can lead to some confusion:
class Foo
{
int a, b;
public:
void Set(int a, int b)
{
a = a; // Erh,
b = b; // wat???
}
};
There are many ways to work around this, but one of the most common is to prefix member variables with m_.
Your code runs afoul of this, apparently the original in C passed the array to heapify, and the array was in a local variable a. When you made a into a member, leaving the variable name exactly the same allowed you not to miss the fact that you no-longer need to pass it to the object (and indeed, your heapify member function no-longer takes an array as a pointer, leading to one of your compile errors).
The next problem we encounter, not directly part of your problem yet, is your function Heap(). Firstly, it is private - you used class and haven't said public yet. But secondly, you have missed the significance of this function.
In C++ every struct/class has an implied function of the same name as the definition. For class Heap that would be Heap(). This is the 'default constructor'. This is the function that will be executed any time someone creates an instance of Heap without any parameters.
That means it's going to be invoked when the compiler creates a short-term temporary Heap, or when you create a vector of Heap()s and allocate a new temporary.
These functions have one purpose: To prepare the storage the object occupies for usage. You should try and avoid as much other work as possible until later. Using std::cin to populate members in a constructor is one of the most awful things you can do.
We now have a basis to begin to write the outer-shell of the code in a fashion that will work.
The last change is the replacement of "HEAPSIZE" with a class enum. This is part of encapsulation. You could leave HEAPSIZE as a #define but you should expose it within your class so that external code doesn't have to rely on it but can instead say things like Heap::Size or heapInstance.size() etc.
#include <iostream>
#include <cstdint> // for size_t etc
#include <array> // C++11 encapsulation for arrays.
struct Heap // Because we want to start 'public' not 'private'.
{
enum { Size = 10 };
private:
std::array<int, Size> m_array; // meaningful names ftw.
public:
Heap() // default constructor, do as little as possible.
: m_array() // says 'call m_array()s default ctor'
{}
// Function to load values from an istream into this heap.
void read(std::istream& in)
{
for (size_t i = 0; i < Size; ++i)
{
in >> m_array[i];
}
return in;
}
void write(std::ostream& out)
{
for (size_t i = 0; i < Size; ++i)
{
if (i > 0)
out << ','; // separator
out << m_array[i];
}
}
int heapify(size_t index)
{
// implement your code here.
}
}; // <-- important.
int main(int argc, const char* argv[])
{
Heap myHeap; // << constructed but not populated.
myHeap.load(std::cin); // read from cin
for (size_t i = 1; i < myHeap.Size; ++i)
{
myHeap.heapify(i);
}
myHead.write(std::cout);
return 0;
}
Lastly, we run into a simple, fundamental problem with your code. C++ does not have implicit multiplication. 2i is the number 2 with a suffix. It is not the same as 2 * i.
int l = 2 * i;
There is also a peculiarity with your code that suggests you are mixing between 0-based and 1-based implementation. Pick one and stick with it.
--- EDIT ---
Technically, this:
myHeap.load(std::cin); // read from cin
for (size_t i = 1; i < myHeap.Size; ++i)
{
myHeap.heapify(i);
}
is poor encapsulation. I wrote it this way to draw on the original code layout, but I want to point out that one reason for separating construction and initialization is that it allows initialization to be assured that everything is ready to go.
So, it would be more correct to move the heapify calls into the load function. After all, what better time to heapify than as we add new values, keeping the list in order the entire time.
for (size_t i = 0; i < Size; ++i)
{
in >> m_array[i];
heapify(i);
}
Now you've simplified your classes api, and users don't have to be aware of the internal machinery.
Heap myHeap;
myHeap.load(std::cin);
myHeap.write(std::cout);