Preprocessor ## pasting operator - c++

What I am trying to achieve is creation of these three classes as mentioned in the code but just trying to use pre-processer in handy so that these similar classes can be created and executed rather than writing individual codes for them:
#include <iostream>
#define MYMACRO(len,baselen)
using namespace std;
class myclass ## len
{
int MYVALUE ## baselen;
public:
myclass ## len ## ()
{
cout << endl;
cout << " For class" ## len ## "'s function 'myFunction" ## len ## "' the value is: " << MYVALUE ## baselen << endl;
}
};
int main()
{
MYMACRO(10,100)
//myclass10 ob1;
MYMACRO(20,200)
//myclass20 ob2;
MYMACRO(30,300)
//myclass30 ob3;
myclass10 ob1;
myclass20 ob2;
myclass30 ob3;
cout << endl;
return 0;
}
Now I don't know whether the it can be done & since I am getting this error. If yes then please someone solve the error and enlighten me if no then please give the reason for the same so I am also reassured that we are on same page! The error is:
[root#localhost C++PractiseCode]# g++ -o structAndPreprocessor structAndPreprocessor.cpp
structAndPreprocessor.cpp:5: error: invalid token
structAndPreprocessor.cpp:6: error: invalid function declaration
structAndPreprocessor.cpp:7: error: invalid token
structAndPreprocessor.cpp:9: error: invalid token
structAndPreprocessor.cpp:9: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp: In function `int main()':
structAndPreprocessor.cpp:25: error: `myclass10' was not declared in this scope
structAndPreprocessor.cpp:25: error: expected `;' before "ob1"
structAndPreprocessor.cpp:26: error: `myclass20' was not declared in this scope
structAndPreprocessor.cpp:26: error: expected `;' before "ob2"
structAndPreprocessor.cpp:27: error: `myclass30' was not declared in this scope
structAndPreprocessor.cpp:27: error: expected `;' before "ob3"
[root#localhost C++PractiseCode]#

You need to use \ at each end of your line to define your macro (and likely remove the using statement from the macro)
using namespace std;
#define MYMACRO(len,baselen) \
class myclass ## len \
{ \
int MYVALUE ## baselen; \
(...snip...) \
}\
};
Note the absence of escape on last line
Most likely you're doing Cpp and using Macros is discouraged. You'd better use either templates or traditional dynamic code (dpeending on your needs). Compared to macros, template bring the additional type checking at compilation and provide much more readable error messages.

The macro solution you present is a solution I've used before, but I would look at approaching this differently. The macro solution is a unwieldy and difficult to maintain and debug for all but the most trivial code.
Have you thought about generating the code you need from a template? Using Cheetah or Mako to fill out a source template would be quite a bit cleaner, and you could drive the generation from a configuration file, so you don't have to hand-maintain your list of classes.
You'd have a myclass.tmpl template file that looks something like this :
#for len, baselen in enumerate(mylist_of_classes_i_want_to_generate)
class MyClass$len
{
int MYVALUE$baselen;
public:
MyClass$len()
{
cout << endl;
cout << " For class $len's function 'myFunction $len' the value is: " << MYVALUE$baselen << endl;
}
};
#end for
You'd then call cheetah to autogenerate the code at the start of your build flow prior to compilation.

Related

Creating a function that opens a file and reads it using ifstream and ofstream but its QT says i didnt declare the function

Trying to make a function that opens a file using ifstream and offstream but QT compiler tells me my variables are not declared. program is alot longer but its this specific part causing error.
I need to make the function to receive the declared variables in the main code to be able to open the file later on.
Cant Use global variables.
I can make program run without using functions but its a must.
/home/eip/Desktop/atm/ATMFINAL/main.cpp:18: error: variable or field 'OpenUserFile' declared void
/home/eip/Desktop/atm/ATMFINAL/main.cpp:18: error: 'load' was not declared in this scope
/home/eip/Desktop/atm/ATMFINAL/main.cpp:18: error: expected primary-expression before ',' token
void OpenUserFile(load&, ReceiptCreator&,Save&)
^
/home/eip/Desktop/atm/ATMFINAL/main.cpp:18: error: 'ReceiptCreator' was not declared in this scope
void OpenUserFile(load&, ReceiptCreator&,Save&)
^//////////
/home/eip/Desktop/atm/ATMFINAL/main.cpp:18: error: expected primary-expression before ',' token
void OpenUserFile(load&, ReceiptCreator&,Save&)
^////////////
/home/eip/Desktop/atm/ATMFINAL/main.cpp:18: error: 'Save' was not declared in this scope
void OpenUserFile(load&, ReceiptCreator&,Save&)
^/////////
/home/eip/Desktop/atm/ATMFINAL/main.cpp:18: error: expected primary-expression before ')' token
void OpenUserFile(load&, ReceiptCreator&,Save&)
^
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cstdlib>
#include<ctime>
using namespace std;
void OpenUserFile(load&, ReceiptCreator&,Save&){
load.open("id.txt"); // reads id.txt.
if(load.fail()){ //If file has problems, user receives an error message
cout<< "Error reading user id" <<endl;
}
ofstream& ReceiptCreator,Save; // instruction to create a file.
ReceiptCreator.open("receipt.txt", ios::app); //prints out output to external .txt file.
if(ReceiptCreator.fail()){ //if error reading display, error message
cout<< "Error printing transaction receipt" <<endl;
}
}
int main(){
time_t C = time(0); // uses computers curren time
string CT = ctime(&C);// shows user current time
string account, userName, SocialSec, PassNum, UserBalance,Bankname, FirstName;
string LastName, AccountNum, SocialNum;//
int PassFile, PassUser,WithDrawal; // variables for user password
double InitialBalance,Deposit, CurrentBalance;// variables for aritmethic calculations
unsigned ATMNUM = 100+rand()%500; // randomizes atm number
int receipt,process, UI = -99, retry = 1; //
ofstream ReceiptCreator,Save;
ifstream load; // starts process to read user information.
int OpenUserFile(load&, ReceiptCreator&,Save&);
cout << "Loading data from file..." << endl;
void foo(int x){} Is a function with one argument of type int.
void foo(int){} Is a function with one unnamed argument of type int.
void OpenUserFile(load&, ReceiptCreator&,Save&){} Is a function with unnamed arguments of type load&, ReceiptCreateor& and Save&. However those are no types in your code. I'll leave it to you to figure out the correct signature.
You have to fix the errors one by one, because one error can confuse the compiler and trigger other errors. One more problem I can spot now is
ofstream& ReceiptCreator,Save;
References cannot be not initialized. I suppose this line was just a trial to fix the code, as the names are those of the arguments, then you can remove that line. If not, you need to decide whether to pass the streams as arguments or have them only inside the function, not both.

How to declare a reference to a member in the same class?

I looked at a lot of other questions and answers and no one seems to have the same question I do.
I am trying to make references to variables, both within a class. I took out the part of the larger program I am writing and isolated it in a little file: test.cpp. I thought maybe my problem had something to do with how I was using the variable with the reference, but the same messages appeared as in the larger program.
Here is my code:
#include <iostream>
class Test {
public:
int test;
int& rtest = test;
};
int main() {
std::cout << "Enter an integer: ";
std::cin >> Test.rtest;
std::cout << "\n" << Test.rtest << "\n";
return 0;
}
I received these messages:
warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
int& rtest = test;
In function ‘int main()’: error: expected primary-expression before ‘.’ token
std::cin >> Test.rtest;
error: expected primary-expression before ‘.’ token std::cout << "\n" << Test.rtest << "\n";
Why am I getting these? Is what I am trying to do possible? If so, how can I do it?
warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 int& rtest = test;
You need to pass the flag -std=c++11 to your compiler, otherwise it defaults to an older version of C++ which doesn't allow you to initialize class members in that way.
In function ‘int main()’: error: expected primary-expression before ‘.’ token std::cin >> Test.rtest;
error: expected primary-expression before ‘.’ token std::cout << "\n" << Test.rtest << "\n";
This is because the . operator wants an instance of your class, not the class itself (that's what :: would be for). Declare e.g. Test test; and use test.rtest instead.
You need to have an instance of Test to access non static members of a class:
int main() {
Test t; // <<<<<<<<
std::cout << "Enter an integer: ";
std::cin >> t.rtest;
std::cout << "\n" << t.rtest << "\n";
}
Also you need to initialize the reference with an appropriate constructor, unless you have the -std=c++11 compiler flag enabled as the error message says:
class Test {
public:
int test;
int& rtest; // Nope! = test;
Test() : test(), rtest(test) {} // <<<<<<<<<<<<<<<<<<
};

Defining functions using backslash in c++

I saw people using backslash when they define functions in Macros as:
#define ClassNameNoDebug(TypeNameString) \
static const char* typeName_() { return TypeNameString; } \
static const ::Foam::word typeName
I did a very easy test. But I got a bunch of errors. The testing code is as follows:
In my testmacro.h file:
#define declearlarger(first,second) \
double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}
In my main() function:
int second =2;
int first =1;
cout << declearlarger(first,second) << endl;
The errors are:
/home/jerry/Desktop/backslash/backslash_test/testmacro.h:7: error: expected primary-expression before 'double'
double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}
^
/home/jerry/Desktop/backslash/backslash_test/testmacro.h:7: error: expected ';' before 'double'
double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}
^
/home/jerry/Desktop/backslash/backslash_test/main.cpp:24: error: expected primary-expression before '<<' token
cout << declearlarger(first,second) << endl;
^
That concludes all my testing errors. Can anyone give some suggestions why these errors pop up?
You're trying to use a function definition (generated by your macro) inside an expression. C++ does not allow such a thing. You could instead define your macro to be
#define declearlarger(first,second) \
(((first)>(second)) ? (first) : (second))
and then it would work. Also note that none of the errors come from the backslash, they are all generated because of the function definition/expression clash.

GCC cannot compile: '* does not name a type'

Today, after Slackware 13.37 installation, i've got the problem: default GCC 4.5.2 cannot compile my code. Now I study C++ by the Stephen Davis's book "C++ for dummies" and want to compile this:
#include <stdio.h>
#include <iostream.h>
int main(int nNumberofArgs, char* pszArgs[])
{
int nNCelsius;
cout << "Celsisus: ";
cin >> nNCelsius;
int nNFactor;
nNFactor = 212 - 32;
int nFahrenheit;
nFahrenheit = nNFactor * nNCelsius / 100 + 32;
cout << "Fahrenheit: ";
cout << nFahrenheit;
return 0;
}
But my GCC 4.5.2 gives these errors:
FahTCel.cpp:7:14: error: expected ')' before ';' token
FahTCel.cpp:7:14: error: 'main' declared as function returning a function
FahTCel.cpp:8:1: error: 'cout' does not name a type
FahTCel.cpp:9:1: error: 'cin' does not name a type
FahTCel.cpp:12:1: error: 'nNFactor' does not name a type
FahTCel.cpp:15:1: error: 'nFahrenheit' does not name a type
FahTCel.cpp:17:1: error: 'cout' does not name a type
FahTCel.cpp:18:1: error: 'cout' does not name a type
FahTCel.cpp:20:1: error: expected unqualified-id before 'return'
FahTCel.cpp:21:1: error: expected declaration before '}' token
Three errors:
The correct header is <iostream>. This program requires no other headers.
You must either put using namespace std; in the file, or refer to std::cout and std::cin explicitly. Take your pick, plenty of C++ programmers disagree about which of the two options is better. (You could also bring just cin and cout into your namespace, if you wanted.)
The program does not write a line terminator at the end. This will cause the output to "look bad" on most terminals, with the command prompt appearing on the same line as the output. For example:
Here are the corrections:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
...
cout << nFahrenheit << '\n';
...
}
Note: It is extremely unusual to see main take parameters with names other than argc and argv. Changing the names just makes it harder for other people to read your code.
its std::cout or you should add using namespace std;
and the include should be < iostream> not < ionstream.h>.

namespaces ; expected unqualified id before ')' token ; invalid use of struct

I am new to c++ and am trying to understand namespaces and how they work
I thought i'd code up a simple "hello world" program using namespaces but as it turned
out, it seems to have backfired on me and i am getting a bunch of weird errors.
Here is my code:
#include <iostream>
namespace names
{
using namespace std;
void class hello() //line 7 <-- here is where the compiler is complaining
about the 'unqualified id'
{
cout <<"Hello World";
}
}
int main()
{
names::hello(); //line 16
}
And here is the output:
E:\CB_Workspace\Names\names_main.cpp|7| error: expected unqualified-id before ')' token|
E:\CB_Workspace\Names\names_main.cpp|| In function 'int main()':|
E:\CB_Workspace\Names\names_main.cpp|16| error: invalid use of incomplete type 'struct names::hello'|
E:\CB_Workspace\Names\names_main.cpp|7| error: forward declaration of 'struct names::hello'|
||=== Build finished: 3 errors, 0 warnings ===|
I am not sure what is going on and I have tried to search through other posts on this error.
The other post i found on this did not really address the context of namespaces.
g++ error - expected unqualified-id before ')' token
Any help would be much appreciated. Thank you
edit: ok thanks guys. I removed the "class" under my namespace and it works now. I'll flag it to be closed now. Thanks for the help
You are not trying to write a class there. A class is different than a function. Please try:
void hello()
This has nothing to do with namespace.
In C/C++ the rule for declaring a function is:
returnType functionName(functionArgument1,functionArgument2,...);
Your way of declaring the function does not follow the C/C++ rule. What you have is:
void class hello();
It should be:
void hello();
Probably you are confusing it with syntax to define the function outside the class body. In that case the rule is:
returnType className::functionName(functionArgument1, functionArgument2,...)
{
}
Namespace does not affect how function is declared. It defines where the function is available
void class hello()
Huh? How can a function also be a class? Just remove that:
void hello()