Error in constructor - C++ -
i have learnt object oriented programming concepts in python, want transfer knowledge c++, , have trouble basic implementation used easy using python.
#include<iostream> using namespace std; class animal{ char name; int age; public: animal(char name, int age); }; animal::animal(char name, int age) { this->name = name; this->age = age; } int main() { animal dog ("megg", 10); cout << "name: " dog.name <<endl; return 0; }
when compile code, lot of messages, such as:
error: no matching function call 'animal::animal(const char[5], int)' note: animal::animal(char, int) <near match> note: candidate expects 1 argument, 2 provided
thanks!
you don't need this->name = name in constructor definition
"megg" string literal. can cast "megg" const char * not char (this causing error).
or better yet. can use c++ standard library string class std::string
#include <iostream> #include <string> class animal{ std::string name; int age; public: animal(std::string name, int age); std::string getname() const; int getage() const; }; animal::animal(std::string name, int age) { name = name; age = age; } std::string animal::getname() const { return name; } int animal::getage() const { return age; } int main() { animal dog ("megg", 10); std::cout << "name: " << dog.getname() << std::endl; // error in line. missing << between "name: " , dog.name return 0; }
some additional edits:
you should avoid using using namespace std
takes in standard library (from files you've included) , puts in global namespace. can instead use scope resolution operator ::
seen above.
when start working multiple libraries may encounter both have class named vector or string, or functions same name. way avoid specify namespace want use.
or alteratively can following:
using std::cout; using std::endl; using std::string;
additionaly in order program work need way access object's member variables. making variables public or better practice add accessor functions.
Comments
Post a Comment