c++ .h and .cpp files - about methods -


hi.

how can define bool method in .h file , work in cpp file? have

my.h

#include <string>  public class me; class me { public: me();  private bool method(string name); //it ok??  } 

my.cpp

#include 'my.h'; me::me() { method(string name); //can this? isn't there alternative? }  method (string name) { cout<<"name"<<endl; } 

is not working.why?

there number of issues code.

my.h

#include <string>  // public class me; // absolutely not needed. language did this?  class me { public: me();  private: // need colon here.   bool method(string name); //it ok?? // no. class called std::string. should pass const-reference (const std::string& name);  } 

my.cpp

#include 'my.h'; me::me() { // `name` undefined here. don't need specify type. //method(string name); //can this? isn't there alternative?      method("earl"); }  // method (string name) // see previous comment const-reference , name of class. note c++ case-sensitive. need specify return type , class name: bool me::method(const std::string& name) {     // cout<<"name"<<endl; // close...     std::cout << "my name " << name << std::endl;     return true; // returning `bool, right? } 

you'll need call code:

int main() {     me instance_of_me;     return 0; } 

i suggest take a c++ tutorial , some reading material.

answers questions in comments:

could please tell me why need pass std::string through reference?

this question has been asked (more once) on stackoverflow. recommend this answer.

and me mo?

in hindsight mo terrible choice variable name. instance_of_me may have been better choice. line constructs instance of me, calling constructor (which in turn calls method("earl"))

you meant me method("hello"); in main()

i did not!

you declared method private member function. method cannot, therefore, called outside class.


Comments