HI.
How can I define a bool method in .h file and work with it in the cpp file? I have
my.h
#include <string>
public class me;
class me
{
public:
me();
private bool method(string name); //it is ok??
}
my.cpp
#include 'my.h';
me::me()
{
method(string name); //can i do this? isn't there another alternative?
}
method (String name)
{
cout<<"name"<<endl;
}
is not working.why?
I suggest you learn the basics of C++ from a tutorial
my.h
#include <string>
class me
{
public:
me();
bool method(std::string name) const;
};
my.cpp
#include 'my.h';
me::me()
{
}
bool me::method(std::string name)
{
std::cout << name << std::endl;
}
As written, there is no need for me::method to be a member function (it could be a static).
Numerous little fixes there. I get the sense that you are coming from C# (possibly java). Read up on the differences. Google has good sources :)
There are a number of issues with your code.
my.h
#include <string>
// public class me; // Absolutely not needed. From which language did you get this?
class me
{
public:
me();
private: // You need the colon here.
bool method(string name); //it is ok?? // No. The class is called std::string. You should pass it by const-reference (const std::string& name);
}
my.cpp
#include 'my.h';
me::me()
{
// `name` is undefined here. You also don't need to specify the type.
//method(string name); //can i do this? isn't there another alternative?
method("earl");
}
// method (String name) // See previous comment about const-reference and the name of the class. Also note that C++ is case-sensitive. You also need to specify the return type and the class name:
bool me::method(const std::string& name)
{
// cout<<"name"<<endl; // Close...
std::cout << "My name is " << name << std::endl;
return true; // we are returning a `bool, right?
}
You'll also need to call your code:
int main()
{
me instance_of_me;
return 0;
}
I suggest you take a look for a good C++ tutorial and some reading material.
could you please tell me why do I need to pass std::string through reference?
This question has already been asked (more than once) on StackOverflow. I recommend this answer.
And what is with me mo?
In hindsight mo was a terrible choice for a variable name. instance_of_me may have been a better choice. This line constructs an instance of me, calling the constructor (which in turn calls method("earl"))
You meant me method("hello"); in the main()
I certainly did not!
You declared method as a private member function. This method cannot, therefore, be called from outside the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With