C++ 权限控制

C++ 中权限控制防止误修改

C++权限:

  • public
  • protected
  • private 默认权限

this 表示当前对象

#include <stdio.h>

class Student {
private:
	char *name;
	int age;
	
public:
	void setName(char *name)
	{
		this->name = name;
	}

	int setAge(int age)
	{
		if ( age >= 0 && age < 100)
		{
			this->age = age;
		}
		else
		{
			this->age = 0;
			return -1;
		}
		
		return 0;
	}

	void printInfo(void)
	{
		printf("name = %s, age = %d\n", name, age);
	}
};

int main(int argc, char**argv)
{
	Student stu;

	stu.setName("zhangsan");
	stu.setAge(120);
	stu.printInfo();

	return 0;
}

setAge 做了保护工作,防止输入错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个简单的权限控制C++实现代码。 ```c++ #include <iostream> #include <string> using namespace std; class User { private: string username; string password; int permissionLevel; public: User(string username, string password, int permissionLevel) { this->username = username; this->password = password; this->permissionLevel = permissionLevel; } bool checkPassword(string password) { return this->password == password; } int getPermissionLevel() { return permissionLevel; } }; class PermissionController { private: User* currentUser; public: PermissionController() { currentUser = nullptr; } bool login(string username, string password) { // 这里省略了从数据库中获取用户信息的步骤 User* user = new User(username, password, 0); // 假设获取到了用户信息 if (user->checkPassword(password)) { currentUser = user; return true; } delete user; return false; } void logout() { if (currentUser != nullptr) { delete currentUser; currentUser = nullptr; } } bool hasPermission(int requiredPermissionLevel) { if (currentUser == nullptr) { return false; } return currentUser->getPermissionLevel() >= requiredPermissionLevel; } }; int main() { PermissionController pc; pc.login("admin", "123456"); if (pc.hasPermission(1)) { cout << "User can perform action with permission level 1." << endl; } else { cout << "User does not have sufficient permission level." << endl; } pc.logout(); return 0; } ``` 在上述代码中,定义了一个 `User` 类来表示用户,包括用户名、密码和权限等级。另外还定义了一个 `PermissionController` 类来进行权限控制,其中包括用户登录、注销和检查权限等方法。在 `main` 函数中,我们可以通过 `PermissionController` 对象来进行登录和检查权限操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值