explicit-keyword enforces only explicit casts to be valid
Protected members are accessible in the class that defines them and in classes that inherit from that class.
Protected members only accessible within the class defining them.
All the above are wrong
class MyClass { public: explicit MyClass(int x) { // 构造函数代码 } }; void func(MyClass obj) { // 函数体 } int main() { MyClass obj1(5); // 正确,显式调用构造函数 MyClass obj2 = 10; // 错误,不能进行隐式类型转换 func(15); // 错误,不能进行隐式类型转换 return 0; }
class MyBaseClass { protected: int protectedVar; }; class MyDerivedClass : public MyBaseClass { public: void func() { protectedVar = 10; // 正确,派生类中可以访问受保护的成员 } }; int main() { MyBaseClass obj; obj.protectedVar = 5; // 错误,受保护的成员在类的外部不可访问 return 0; }