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;
}
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 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
I am writing a small game for an assignment and it requires using a map, I have successfully put the map into a 2d array, but now working further into the assignment I found I need to access the array Map[][] in another function. I have tried to get it to work but failed. The error I get with g++ is " error: 'Map' is not a type " Any help would be appreciated.
I have searched but either I am terrible at using the search engine or I couldn't find anything specific to this error.
const int MapSZ = 10; //In Global
int Map[MapSZ][MapSZ]; // Also Global
void GetMap(ifstream&, int); //Getting the map (Proto)
GetMap(fin, Map[MapSZ][MapSZ]); //In the main function.
void GetMap(ifstream& fin, Map[MapSZ][MapSZ]) //Inserting the map into an array
void GetMap(ifstream& fin, Map[MapSZ][MapSZ])
should be:
void GetMap(ifstream& fin, int Map[MapSZ][MapSZ])
^^^^
Notice, that Map is the name of the array, but you didn't mention its type.
If Map[MapSZ][MapSZ] is defined as a global, as your comment states (i.e. it is defined in main.cpp but outside of the main function), there is no need to pass it as a parameter to GetMap. You could simply do something like
void GetMap(ifstream& fin); //proto
int main(int argc, const char * argv[]) {
GetMap(fin);
}
void GetMap(ifstream& fin) {
//some code that uses Map[MapSZ][MapSZ]
}
Let me set the scene..
You can open files in a specific mode like this:
#include <fstream>
int main(){
std::fstream myfile;
myfile.open ("filename", std::ios::app);
return 0;
}
that second parameter is an enumerated type-
which is why you will get a compiler error attempting this:
#include <fstream>
int main(){
std::fstream myfile;
myfile.open ("filename", std::ios::lksdjflskdjflksff);
return 0;
}
In this example, the class doesn't have to account for the second parameter being incorrect, and the programmer never has to worry about passing in a nonsensical value.
Question: Is there a way to write functions that must take a particular type AND a particular value?
Let's say I wanted to re-implement a File Handling class similar to the one above.
The difference is I'm making the second parameter a char instead of an enumerated type.
How could I get something like this to work:
#include "MyFileHandler.h"
int main(){
MyFileHandler myfile1;
myfile.open ("filename", 'a'); //GOOD: a stands for append
myfile.open ("filename", 't'); //GOOD: t stands for truncate
myfile.open ("filename", 'x'); //COMPILER ERROR: openmode can not be the value 'x'
return 0;
}
Going beyond this, can I get the compiler to test the validity of argument values through functional means?
Example:
void IOnlyAcceptPrimeNumbers(const int & primeNumber);
int function(void);
int main(){
IOnlyAcceptPrimeNumbers(3); //GOOD: 3 is prime
IOnlyAcceptPrimeNumbers(7); //GOOD: 7 is prime
IOnlyAcceptPrimeNumbers(10); //COMPILER ERROR: 10 is not prime
IOnlyAcceptPrimeNumbers(10+1); //GOOD: 11 is prime
IOnlyAcceptPrimeNumbers(1+1+1+1); //COMPILER ERROR: 4 is not prime
IOnlyAcceptPrimeNumbers(function()); //GOOD: can this somehow be done?
return 0;
}
void IOnlyAcceptPrimeNumbers(const int & primeNumber){return;}
int function(void){return 7;}
I believe i've made it clear what I want to do and why I find it important.
Any solutions out there?
If you want compile-time checked values, you could write templates rather than function arguments:
template <char> void foo(std::string const &); // no implementation
template <> void foo<'a'>(std::string const & s) { /* ... */ }
template <> void foo<'b'>(std::string const & s) { /* ... */ }
Usage:
foo<'a'>("hello world"); // OK
foo<'z'>("dlrow olleh"); // Linker error, `foo<'z'>` not defined.
If you want an actual compiler error rather than just a linker error, you could add a static_assert(false) into the primary template.
No, if you specify that your function will take a char, it will take any char.
The "resolution" used by the compiler for checking passed arguments is the type rather than a set of possible values.
In other words, you need to use enumerations for this, or move the checking to runtime, or do something horrid like:
static void processAorT (char typ, char *fileName) { ... }
void processA (char *fileName) { processAorT ('a', fileName); }
void processT (char *fileName) { processAorT ('t', fileName); |
(not something I would advise, by the way).
Having said that, I'm not sure what you're proposing is a good idea anyway.
The compiler may be able to detect invalid constants, but won't be very successful if the parameter passed into IOnlyAcceptPrimeNumbers has come from a variable or, worse, input by a user.
The API is a contract between caller and function and, if the rules of that contract are not followed, you're free to do whatever you want, though hopefully you'd document it.
In other words, that function should begin:
void IOnlyAcceptPrimeNumbers (int num) {
if (!isPrime (num)) return;
// do something with a prime number.
}
(or the equivalent for your function that accepts a and t but not x). Doing nothing when passed invalid parameters is a reasonable strategy, as is returning an error or throwing an exception (though no doubt some would argue with this).
How you handle it is up to you, but it needs to be handled at runtime simply because the compiler doesn't have all the information.
You can only check value validity at runtime. Best you can do is use assert to stop programm execution if precondition is violated.
No. If you want to restrict the accepted arguments you need to use enums or accept an object that inherits from a specific interface (depends how sophisticated you want to make it). Enums is the common way to address this issue.
The example about the IOnlyAcceptPrimeNumbers is not well designed. If you want to achieve something similar it would be better to provide a class method that is something such as bool setNumber(int number) that will return false if the number is not prime. If you want to do it in the costructor the real alternative is to throw an exception (that is not really nice to do).
The concept is that you can not simply rely that the user will pass you only elements from a (correct) subset of the values that the parameter type allows.
While more restrictive than your requirements (this limits the values a particular type can hold), you can always try something like:
// Vowel.h
#ifndef VOWEL_H_
#define VOWEL_H_
class Vowel
{
public:
static const Vowel A;
static const Vowel E;
static const Vowel I;
static const Vowel O;
static const Vowel U;
char get() const { return value; }
private:
explicit Vowel(char c);
char value;
};
#endif /* VOWEL_H_ */
// Vowel.cpp
#include "Vowel.h"
Vowel::Vowel(char c) : value(c) {}
const Vowel Vowel::A('A');
const Vowel Vowel::E('E');
const Vowel Vowel::I('I');
const Vowel Vowel::O('O');
const Vowel Vowel::U('U');
Since the char constructor is private, only Vowel itself can construct objects from chars. All other uses are done by copy construction or copy assignment.
(I think I originally learned this technique from Scott Meyers; thank him / blame me.)