Use a function in different file and different namespace in Visual C++ - c++

I am struggling with my first steps in C++. Already asked this question, but did not get the full answer specifically about namespace.
I did the following.
In Visual Studio 2015 created am empty project(New Project -> Visual C++ -> Empty Project)
Then I added two files in Source.cpp and PrintFunc.cpp whose respective contents are as follows.
Source.cpp
#include <iostream>
using namespace std;
int PrintHello();
extern int tempCount;
void main()
{
int i;
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
PrintFunc.cpp
#include <iostream>
using namespace std;
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
This is compiling perfectly.
Now I am learning about namespaces, so I just tried to put the contents of the second file in a namespace as follows.
PrintFunc.cpp (modified)
#include <iostream>
using namespace std;
namespace MyNameSpace
{
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
}
And now I modified the Source.cpp also to reflect the namespaces introduction in the previous snippets.
#include <iostream>
using namespace std;
int MyNameSpace::PrintHello();
extern int MyNameSpace::tempCount;
void main()
{
int i;
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
This simply does not compile. Can someone please kindly correct me. My objective is to understand namespace concept in c++. Also I have good exp with C#.

The problem that compiler does not know about namespace MYSpace when compiling Source.cpp.
#include <iostream>
using namespace std;
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
int main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
But this sample is useless. It work only because you have only one consumer .cpp.
You should use .h file and then include it (PrintFunc.h) in Source.cpp and any other .cpp when you want to use that funtions.
I'll write an example:
Print.h
#pragma once
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
Notice that we dont't use additional includes and using namespace here. We would use includes only to use some classes in functions interfaces.
using namespace could "spoil" consumer's .cpp or .h.
Print.cpp
#include <iostream>
#include "Print.h"
using namespace std;
int MyNameSpace::tempCount = 111;
int MyNameSpace::PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
Here we can set any include it will not touch any other files.
And consumer .cpp:
#include <iostream>
#include "Print.h"
using namespace std;
int main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
VS specific: #pragma once and for VS you have to #include "stdafx.h" at first line in any .cpp

You have to supply namespace name when using its members. Or use using namespace directive.
void main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
However, for it to work namespace should be declared in the separate .h file and it should be included in your source.cpp

So finally here it is that I have settled for based on Dmitriy Zapevalov answer.
First Print.h
#pragma once
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
Next PrintFunc.cpp
#include <iostream>
#include "Print.h"
using namespace std;
namespace MyNameSpace
{
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
}
PrintFunc.cpp can also be like this as an alternative.
PrintFunc.cpp (alternative)
#include <iostream>
#include "Print.h"
using namespace std;
int MyNameSpace::tempCount = 111;
int MyNameSpace::PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
And finally Source.cpp
#include <iostream>
#include "Print.h"
using namespace std;
using namespace MyNameSpace;
void main()
{
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
Source.cpp can also be like this as an alternative.
Source.cpp (alternative)
#include <iostream>
#include "Print.h"
using namespace std;
void main()
{
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}

Related

C++ bitset strange value [duplicate]

This question already has answers here:
Using scanf/printf to input into/output from a bitset
(3 answers)
Closed 5 months ago.
#include <bitset>
#include <assert.h>
#include <stdio.h>
using namespace std;
int main()
{
bitset<128> bs(42);
bs[11]=0;
bs[12]=1;
assert(bs[12]==1);
printf("bs[11]=%d\n", bs[11]);
printf("bs[12]=%d\n", bs[12]);
return 0;
}
console output:
Why can't I simply get 0 or 1 as output ?
printf with %d is for integer values, whereas std::bitset::operator[] returns a std::bitset::reference.
You can use std::cout from <iostream> header (which is anyway a more c++ "way" to print to the console):
#include <bitset>
#include <assert.h>
#include <iostream>
int main()
{
std::bitset<128> bs(42);
bs[11] = 0;
bs[12] = 1;
assert(bs[12] == 1);
std::cout << "bs[11]=" << bs[11] << std::endl;
std::cout << "bs[12]=" << bs[12] << std::endl;
return 0;
}
Output:
bs[11]=0
bs[12]=1
A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
With some review comments :
#include <cassert>
#include <bitset>
#include <iostream>
// anything with a .h extension is probably "C" not "C++"
// #include <assert.h>
//#include <stdio.h>
// using namespace std; <== NO, don't use using namespace std;
int main()
{
std::bitset<128> bs(42);
bs[11]=0;
bs[12]=1;
assert(bs[12]==1);
std::cout <<"bs[11]" << bs[11] << "\n";
std::cout << "bs[12]" << bs[11] << "\n";
return 0;
}
If you are using C++ then don't call printf to output something (my compiler refuse to compile your code correctly).
This C++ code works correctly using iostream:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<128> bs(42);
bs[11]=0;
bs[12]=1;
std::cout << "bs[11]=" << bs[11] << std::endl;
std::cout << "bs[12]=" << bs[12] << std::endl;
return 0;
}

Compiling two projects together in Code Blocks

I'm learning C++ and tutorial asks me to add another project to what I have now.
Also I'm asked to use forward declaration so I can make use of that added file.
Here is my main project:
#include <iostream>
#include "io.cpp"
using namespace std;
int readNumber();
void writeResult(int x);
int main() {
int x = readNumber();
int y = readNumber();
writeResult(x + y);
return 0;
}
here's the added file called io.cpp:
#include <iostream>
using namespace std;
int readNumber() {
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void writeResult(int x) {
cout << "Sum of your numbers is " << x << endl;
}
![And here's a screenshot so you can see what error I'm getting which talks about multiple definition and you can see where those two files are added.
According to the tutorial my code is okay but compiler complains. Why ?]1
In codeblocks, when creating a new class, it should automatically header file. Programming with header files is the best practice out there. Here's the code I tried and it worked, with io.h.
main.cpp
#include <iostream>
#include "io.h"
using namespace std;
io inOut;
int main()
{
int x = inOut.readNumber();
int y = inOut.readNumber();
inOut.writeResult(x + y);
return 0;
}
io.h
#ifndef IO_H
#define IO_H
class io
{
public:
int readNumber();
void writeResult(int);
};
#endif
io.cpp
#include <iostream>
#include "io.h"
using namespace std;
int io::readNumber()
{
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void io::writeResult(int x)
{
cout << "Sum of your numbers is " << x << endl;
}
I used codeblocks to compile the code written above, and it worked perfectly.
Well as turns out when adding more cpps they're not supposed to be #included on the top. That's what makes compiler say that function is being defined multiple times. All I had to do was just get rid off that one line.
Here's my source:
http://www.cplusplus.com/forum/beginner/44651/

Error: expected constructor, destructor, or type conversion before ‘(’ token?

When I compile this I get the error title before my name functions in Name.cpp. I've never seen this error before. What's confusing is that there's already a constructor before the three functions in Name.cpp, since that's what the error seems to be talking about.
main.cpp
#include <iostream>
#include <string>
#include "Name.h"
using namespace std;
int main()
{
}
Name.h
#ifndef NAME_H
#define NAME_H
#include <iostream>
#include <string>
using namespace std;
class Name
{
public:
Name();
string getFirst(string newFirst);
string getMiddle(string newMiddle);
string getLast(string newLast);
void setFirst();
void setLast();
void setMiddle();
private:
string First;
string Middle;
string Last;
};
#endif // NAME_H
Name.cpp
#include "Name.h"
#include <iostream>
#include <string>
using namespace std;
Name::Name()
{
}
Name::setFirst(newFirst){
Name = newFirst;
cout << "You entered: " << Name << endl;
}
Name::setMiddle(newMiddle){
Middle = newMiddle;
cout << "You entered: " << Middle << endl;
}
Name::setLast(newLast){
Last = newLast;
cout<< "You entered: " << Last << endl;
}
You cannot omit type names of arguments. Write ones. Also function prototypes in declaration and definition have to be matched.
Your Name.h should be
#ifndef NAME_H
#define NAME_H
#include <iostream>
#include <string>
using namespace std;
class Name
{
public:
Name();
string getFirst();
string getMiddle();
string getLast();
void setFirst(string newFirst);
void setLast(string newLast);
void setMiddle(string newMiddle);
private:
string First;
string Middle;
string Last;
};
#endif // NAME_H
and Name.cpp should be
#include "Name.h"
#include <iostream>
#include <string>
using namespace std;
Name::Name()
{
}
void Name::setFirst(string newFirst){
Name = newFirst;
cout << "You entered: " << Name << endl;
}
void Name::setMiddle(string newMiddle){
Middle = newMiddle;
cout << "You entered: " << Middle << endl;
}
void Name::setLast(string newLast){
Last = newLast;
cout<< "You entered: " << Last << endl;
}

Run through a vector of member functions in boost for_each

I try to learn boost lambda expressions, and this is a thing that doesn't work out.
How can I run in the for_each a selected member of Holder?
#include <iostream>
#include <string>
#include <boost/assign.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
using namespace std;
using namespace boost::assign;
using namespace boost::lambda;
class Holder
{
public:
void vRun1(std::string s){ cout << "vRun1 " << s << endl; }
void vRun2(std::string s){ cout << "vRun2 " << s << endl; }
void vRun3(std::string s){ cout << "vRun3 " << s << endl; }
};
// --------------------
std::map< std::string, mem_fun_ref_t<void, Holder> > replacer;
insert(replacer)
("buh", std::mem_fun_ref(&Holder::vRun1))
("mar", std::mem_fun_ref(&Holder::vRun2))
("heu", std::mem_fun_ref(&Holder::vRun3));
Holder hol;
How do I call here the functions I have registered in the map<>?
for_each(replacer.begin(), replacer.end(), /* bind(_1, hol, it.first) */ );
The result should be
vRun1 buh
vRun2 mar
vRun3 heu
It looks as though you are overcomplicating it slightly. I'd use boost::function<> like so:
See it live on http://liveworkspace.org/code/b2c5a38d8c3499eefb6330a839a89d0a
#define BOOST_RESULT_OF_USE_DECLTYPE
#include <iostream>
#include <string>
#include <map>
#include <boost/function.hpp>
#include <boost/foreach.hpp>
#include <boost/phoenix.hpp>
using namespace std;
class Holder {
public:
void vRun1(std::string s){ cout << "vRun1 " << s << endl; }
void vRun2(std::string s){ cout << "vRun2 " << s << endl; }
void vRun3(std::string s){ cout << "vRun3 " << s << endl; }
};
typedef std::map< std::string, boost::function<void(Holder&, std::string)> > Replacer;
int main()
{
Replacer replacer;
replacer["a"] = &Holder::vRun1;
replacer["b"] = &Holder::vRun2;
replacer["c"] = &Holder::vRun3;
Holder hol;
for (Replacer::const_iterator it=replacer.begin(); it != replacer.end(); ++it)
{
(it->second)(hol, it->first);
}
Alternatively:
std::cout << "Using BOOST_FOREACH:\n";
BOOST_FOREACH(Replacer::value_type& pair, replacer)
{
(pair.second)(hol, pair.first);
}
Or even:
std::cout << "Using Boost Phoenix:\n";
namespace phx = boost::phoenix;
using namespace phx::arg_names;
std::for_each(replacer.begin(), replacer.end(),
phx::bind(
phx::bind(&Replacer::value_type::second, arg1),
phx::ref(hol),
phx::bind(&Replacer::value_type::first, arg1)));
}
Outputs
vRun1 a
vRun2 b
vRun3 c
Using BOOST_FOREACH:
vRun1 a
vRun2 b
vRun3 c
Using Boost Phoenix:
vRun1 a
vRun2 b
vRun3 c
This works for me:
#include <iostream>
#include <string>
#include <boost/assign.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/function.hpp>
using namespace boost::lambda;
class Holder
{
public:
void vRun1(std::string s){ std::cout << "vRun1 " << s << std::endl; }
void vRun2(std::string s){ std::cout << "vRun2 " << s << std::endl; }
void vRun3(std::string s){ std::cout << "vRun3 " << s << std::endl; }
};
// --------------------
typedef std::map <std::string,
boost::function<void(Holder&, std::string)> > Replacer_t;
Replacer_t replacer;
typedef Replacer_t::value_type ReplacerValue_t;
int main()
{
boost::assign::insert(replacer)
(std::string("buh"), &Holder::vRun1)
(std::string("mar"), &Holder::vRun2)
(std::string("heu"), &Holder::vRun3);
Holder hol;
for_each(replacer.begin(),
replacer.end(),
bind(protect(bind(bind(&ReplacerValue_t::second,_2),
_1,
bind(&ReplacerValue_t::first,_2))),
boost::ref(hol), _1));
}
This took about 2 hours of fighting with boost::lambda. In C++11 I would write it in 30 seconds, so update your compilers accordingly.

C++ accessing global variables/objects in a namespace with a variable/object with the same name

#include <iostream>
#include <string>
using namespace std;
string a;
namespace myNamespace
{
string a;
void output()
{
cout << a << endl;
}
}
int main()
{
a = "Namespaces, meh.";
myNamespace::a = "Namespaces are great!";
myNamespace::output();
}
The result is "Namespaces are great!". So is there any way to access the global string a inside of the namespace myNamespace instead of just the local one?
Like this:
void output()
{
cout << ::a << endl; //using :: = the global namespace
}