← Teaching

C++使用建议

@我不是匠人

  1. const同名成员函数是否构成重载?
  2. const和非const同名成员函数在使用时有何区别?

示例代码

class MyClass {
public:
    void hello() {
        std::cout << "非常量成员函数" << std::endl;
    }
    void hello() const {
        std::cout << "常量成员函数" << std::endl;
    }
};

枚举

  • C语言中的枚举
enum Color {
    Red,
    Green,
    Blue
};
  • C++中的枚举
enum class Color {
    Red,
    Green,
    Blue
};

存在的问题

  1. 会隐式转换为int
  2. 会污染全局命名空间
  3. 没有作用域

区别

  • C语言中的枚举可以被隐式转换
enum Color color = Red;
int i = color; // 正确,因为C语言中枚举可以被隐式转换为整型
  • C++中的枚举不可以被隐式转换
enum class Color: char {
    Red,
    Green,
    Blue
};

Color color = Color::Red;
// int i = color; // 错误,因为C++中的枚举不可以被隐式转换为整型
int i = static_cast<int>(color); // 需要显式转换