类定义
#include <iostream>
#include <string>
using namespace std;
#define PI 3.141592657
class Circle {
//访问权限
//公共权限
public:
//属性
int half_r;
//行为
double cal() { return 2 * PI * half_r; }
};
class Studne {
public:
string name;
int id;
void showUp() {
cout << "name:" << name << endl;
cout << "id:" << id << endl;
};
void setName(string myname) {
name = myname;
}
void setID(int myid) {
id = myid;
}
};
int main() {
//arg1
Circle c1; //实例化
c1.half_r = 20;
int res = c1.cal();
cout << res << endl;
//arg2
Studne s1;
s1.setName("jack");
s1.setID(65535);
s1.showUp();
return 0;
}
类的访问权限
#include <iostream>
#include <string>
using namespace std;
/*
public公共权限:类内YES,类外YES;
protected保护权限:类内YES,类外NOT;
private私有权限:类内YES,类外NOT
*/
class Person {
protected:string username;
private:string passwd;
public:
string name;
int age;
void showInfo() {
passwd = "111";
username = "Could";
cout << "Name:" << name << "Age:" << age <<"Passwd: "<<passwd<< endl;
}
};
int main() {
Person p1;
p1.age = 20;
p1.name = "Ruby";
//p1.passwd = "122";False!
//p1.username = "ss";False!
p1.showInfo();
return 0;
}
类的属性私有化
#include <iostream>
#include <string>
using namespace std;
class Man {
//私有权限,只有内部能控制。
private:
string name;
int age;
string wifeName;
public://外部不能设置值,所以通过public内部一个函数设置私有权限的值。
void setManInfo(string mname, int mage, string wn) {
name = mname;
age = mage;
wifeName = wn;
};
void ShowInfo() {
cout << "He name is " << name << ",and he is " << age << "years old,his wife is " << wifeName << endl;
}
};
int main() {
Man m1;
m1.setManInfo("mick", 33, "cat");
m1.ShowInfo();
return 0;
}