struct和class的访问权限:结构体,类
struct和class 是相同的,唯一的而不同,就是默认权限,struct是public,class默认是private
class Animal {
public://如果不申明权限,默认是私有权限
char name[10];
void eat() {
cout << "age:" << name << endl;
}
};
struct Person1 {
char name[10];
void eat() {
cout << "name:" << name << "吃饭" << endl;
}
};
void test() {
Person1 p1;
p1.name;//struct默认是共有的权限
Animal A1;
A1.name;//不能访问,class默认是私有的权限
}
protected:保护权限,类内部(不包括继承的子类)是可以访问(属性和方法),类外部是不可以访问的
public公有权限:类的外部和内部都可以访问类里面的属性和方法
private:类内部(包括继承的子类)才可以访问,外部不可以访问
#include "pch.h"
using namespace std;
#include <iostream>
#include <string>
//访问权限
class Person2 {
public:
void setage(int n) {
if (n < 0 or n>100) {
cout << "不符合" << endl;
return;
}
age = 43;
};
int getage() {
return age;
}
string getname() {
return name;
}
private:
int age;
string name;
int money;
};
void test02() {
Person2 p1;
p1.setage(132);
age=p1.getage;
name=p1.getname();
};
int main() {
test02();
}