c++ tricks

1 Experiment on virtual keywords

1.1 Changing virtual function access rights in derived classes

Define two classes A, B, where B is publicly derived from A. Define a private member virtual function func in A, and override this function in B, but set its access permission to public

class A{
private:
    virtual void func(){
        printf("A\n");
    }
};
    
class B
    : public A{
public:
    void func(){
        printf("B\n");
    }
    void do_func(){
        func();
    }
};

int main() {
    /* test-1
     * Compilation error, error: 'virtual void A::func()' is private
     * Analysis: It is best not to change the access rights of the virtual modified function in the base class in the derived class, otherwise the polymorphism will be limited, compare test-1 and test-2
    **/
    A * b = new B;
      b->func();

    /* test-2
     * Compile, run successfully,
     * output: B
    **/
    B * b = new B;
    b->func();

    /* test-3
     * Compile, run successfully,
     * output: B
    **/
    A * b = new B;
    b->do_func();

    return 0;
}

2 Enumeration classes

Now there is such a requirement that the constructed objects are based on the established template, and arbitrary construction is not allowed. For example, create a new class for a person's surname, but the surname is fixed, and it is not allowed to construct a new surname, so you can define an enumeration class. Make constructors (copy, assignment) other than Family_Name(const char * name) public. Then define several static Family_Names for users to use.

Note: Enumeration classes cannot be abstract classes

class Family_Name{
private:
    Family_Name(const char * name)
        :name_(name){}
    const char * name_;
public:
    Family_Name(const Family_Name & other){
        name_=other.name_;
    }
    Family_Name & operator=(const Family_Name & other){
        name_=other.name_;
        return *this;
    }
public:
    static Family_Name yang;
    static Family_Name zhang;
    static Family_Name liu;
    static Family_Name zhao;
};

Family_Name Family_Name::yang("yang");
Family_Name Family_Name::zhang("zhang");
Family_Name Family_Name::liu("liu");
Family_Name Family_Name::zhao("zhao");

int main() {
    Family_Name a = Family_Name::yang;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325062247&siteId=291194637