蓝桥ROS机器人之现代C++学习笔记2.6 面向对象

2022-04-29 19:37:04 浏览数 (1)

  1. 委托构造
  2. 继承构造
  3. 显式虚函数重载
  4. 显式禁用默认函数
  5. 强类型枚举
代码语言:javascript复制
#include <iostream>
#include <string>
class Base {
public:
    std::string str;
    int value;
    Base() = delete;
    Base(std::string s) {
        str = s;
    }
    
    // delegate constructor
    Base(std::string s, int v) : Base(s) {
        value = v;
    }
    
    // final constructor
    virtual void foo() final {
        return;
    }
    virtual void foo(int v) {
        value = v;
    }
};
class Subclass final : public Base {
public:
    double floating;
    Subclass() = delete;
    
    // inherit constructor
    Subclass(double f, int v, std::string s) : Base(s, v) {
        floating = f;
    }
    
    // explifict constructor
    virtual void foo(int v) override {
        std::cout << v << std::endl;
        value = v;
    }
};  // legal final

// class Subclass2 : Subclass {
// };  // illegal, Subclass has final
// class Subclass3 : Base {
//    void foo(); // illegal, foo has final
// }

int main() {
    // Subclass oops; // illegal, default constructor has deleted
    Subclass s(1.2, 3, "abc");
    
    s.foo(1);
    
    std::cout << s.floating << std::endl;
    std::cout << s.value << std::endl;
    std::cout << s.str << std::endl;
}
代码语言:javascript复制
#include <iostream>
template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
    return stream << static_cast<typename std::underlying_type<T>::type>(e);
}

// there will be compile error if all define value1 u548c value2
enum Left {
    left_value1 = 1,
    left_value2
};
enum Right {
    right_value1 = 1,
    right_value2
};

enum class new_enum : unsigned int{
    value1,
    value2,
    value3 = 100,
    value4 = 100
};

int main() {
    
    if (Left::left_value1 == Right::right_value2) {
        std::cout << "Left::value1 == Right::value2" << std::endl;
    }
    
    // compile error
    // if(new_enum::left_value1 == 1) {
    //     std::cout << "true!" << std::endl;
    // }
    if (new_enum::value3 == new_enum::value4) {
        std::cout << "new_enum::value3 == new_enum::value4" << std::endl;
    }
    
    std::cout << new_enum::value3 << std::endl;
    
    
    return 0;
}

0 人点赞