MST

星途 面试题库

面试题:C++类成员访问属性的应用

假设有一个C++类`Student`,包含私有成员`int id`,保护成员`string name`,公有成员`void displayInfo()`。请编写代码实现这个类,并在`main`函数中创建对象,尝试访问不同属性的成员,说明哪些可以直接访问,哪些不能直接访问,并解释原因。
26.5万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <string>

class Student {
private:
    int id;
protected:
    std::string name;
public:
    void displayInfo() {
        std::cout << "ID: " << id << ", Name: " << name << std::endl;
    }
    // 构造函数用于初始化成员变量
    Student(int i, const std::string& n) : id(i), name(n) {}
};

int main() {
    Student s(1, "Alice");
    // s.id;  // 错误,私有成员不能在类外直接访问
    // s.name;  // 错误,保护成员不能在类外直接访问
    s.displayInfo();  // 可以直接访问,公有成员在类外可访问

    return 0;
}
  • 直接访问情况
    • displayInfo() 可以在 main 函数中直接访问,因为它是公有成员。公有成员提供了类的外部接口,允许其他代码访问和调用该函数。
  • 不能直接访问情况
    • id 不能在 main 函数中直接访问,因为它是私有成员。私有成员只能在类的内部成员函数中访问,这是为了对类的数据进行封装,防止外部代码随意修改。
    • name 不能在 main 函数中直接访问,因为它是保护成员。保护成员类似私有成员,但允许派生类访问。在类外(非派生类的代码中)不能直接访问,这也是为了数据的封装和保护。