kaguya
kaguya copied to clipboard
About class inheritance
- First define the class
class person {
public:
person() : name("Tom"), age(0) {
}
virtual~person() = default;
person* set_name(const std::string& name) {
this->name = name;
return this;
}
person* set_age(unsigned int age) {
this->age = age;
return this;
}
const std::string& get_name() const{
return this->name;
}
unsigned int get_age() {
return this->age;
}
private:
std::string name;
unsigned int age;
};
class studest : public person {
public:
studest() : person() {
}
virtual~studest() = default;
double get_score() {
return this->score;
}
studest* set_score(double score) {
this->score = score;
return this;
}
private:
double score;
};
- Then register the class
vm["person"]=kaguya::UserdataMetatable<person>()
.setConstructors < person()>()
.addFunction("get_age", &person::get_age)
.addFunction("get_name", &person::get_name)
.addFunction("set_age", &person::set_age)
.addFunction("set_name", &person::set_name)
vm["studest"]=kaguya::UserdataMetatable<studest, person>()
.setConstructors < studest()>()
.addFunction("get_score", &studest::get_score)
.addFunction("set_score", &studest::set_score);
- Running example
local s=studest.new()
s:set_score(74.6):set_name("Jerry"):set_age(14)
The above example sucessfully.
local s=studest.new()
s:set_name("Jerry"):set_age(14):set_score(40)
The above example failed.
- Modify the class definition If the modified class is defined as follows, both examples are successful:
class studest;
class person {
public:
person() : name("Tom"), age(0) {
}
virtual~person() = default;
studest* set_name(const std::string& name) {
this->name = name;
return reinterpret_cast<studest*>(this);
}
studest* set_age(unsigned int age) {
this->age = age;
return reinterpret_cast<studest*>(this);
}
const std::string& get_name() const{
return this->name;
}
unsigned int get_age() {
return this->age;
}
private:
std::string name;
unsigned int age;
};