satoren / kaguya

C++ binding to Lua
Boost Software License 1.0
345 stars 70 forks source link

About class inheritance #89

Open webcpp opened 5 years ago

webcpp commented 5 years ago

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

```cpp
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);
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.


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;
};