C++ 类和对象——封装

访问权限:
公共权限 public 类内可以访问 类外可以访问
保护权限 protected 类内可以访问 类外不可以访问

class Person{
public:
	string name;
protected:
	string car;
private:
	string password; 
public: //类内访问 
	void func(){
	  name = "张三"; 
	  car = "aaac";
	  password = "75557";
	}
};

	
int main(){
	Person p;
	p.func(); 
}

sturct 默认访问权限为 公共;
class 默认访问权限为 私有;

#include <iostream>
using namespace std;

// 定义一个 struct
struct MyStruct {
    int a;       // 默认 public
    void show() {
        cout << "Struct show() 被调用" << endl;
    }
};

// 定义一个 class
class MyClass {
    int a;       // 默认 private
    void show() {
        cout << "Class show() 被调用" << endl;
    }
};

int main() {
    MyStruct s;
    MyClass  c;

    // ? 可以访问 struct 的成员(默认 public)
    s.a = 10;
    s.show();

    // ? 不能访问 class 的成员(默认 private)
    // c.a = 10;    // 编译错误
    // c.show();    // 编译错误

    cout << "Struct 的 a = " << s.a << endl;
    return 0;
}

常用设计模式:私有化变量,公开访问接口

class Person{	
private:
	string name;
	int age;
	bool sex; 
public: //类内访问 
	void set_name(string s){
		name = s; 
	}
	void show_name(){
		cout << "姓名:" << name << endl; 
	}	
	string find_name(){
		return name; 
	}
};
posted @ 2026-05-18 16:29  www6526  阅读(5)  评论(0)    收藏  举报