c里面表示事物的方法
#include <stdio.h>
#include <string.h>
struct Person
{
int age;
char name[128];
};
void Person_eat(struct Person *p)
{
printf("%s eating...\n", p->name);
}
void test01()
{
struct Person p1;
p1.age = 20;
strcpy(p1.name, "bob");
Person_eat(&p1); // bob eating...
}
int main()
{
test01();
return 0;
}
c++中对事物的封装 将属性和行为封装在一起
结构体中所有成员默认都是公有的, 类中的所有成员默认都是私有的,也可以修改成员的访问权限
#include <iostream>
#include <string.h>
using namespace std;
// c++中对事物的封装 将属性和行为封装在一起
// class Person
struct Person
{
// 属性
int age;
char name[128];
// 行为
void Person_eat()
{
printf("%s eating...++\n", name);
}
};
void test01()
{
Person p1;
p1.age = 10;
strcpy(p1.name, "lucy");
p1.Person_eat(); // lucy eating...++
}
int main()
{
test01();
return 0;
}
c++中类中成员权限的设置
#include <iostream>
#include <string.h>
using namespace std;
// 将成员变量设置公有,类外可以随时无控制的改变成员变量的值
class Person
{
public:
int age;
public:
char *name;
};
void test01()
{
Person p1;
p1.age = 10;
p1.name = (char *)malloc(128);
strcpy(p1.name, "bob");
// p1.name = NULL;
cout << p1.name << endl;
}
int main()
{
test01();
return 0;
}
c++中类的封装get set方法
#include <iostream>
#include <string.h>
using namespace std;
class Person
{
public:
void person_init(int age, char *name)
{
if(age >=0 && age <= 100)
{
m_age = age;
}
strcpy(m_name, name);
}
void show_person()
{
cout << m_name << " " << m_age <<endl;
}
int get_age()
{
return m_age;
}
void set_age(int age)
{
if(age >= 0 && age <= 100)
{
m_age = age;
}
}
char * get_name()
{
return m_name;
}
void set_name(char * name)
{
strcpy(m_name, name);
}
private:
int m_age;
char m_name[128];
};
void test01()
{
Person p1;
p1.person_init(20,"lucy");
p1.show_person(); // lucy 20
p1.set_age(30);
p1.set_name("bob");
p1.show_person(); // bob 30
}
int main()
{
test01();
return 0;
}
立方体案例
#include <iostream>
#include <string.h>
using namespace std;
class Cube
{
public:
int getL()
{
return L;
}
int getW()
{
return W;
}
int getH()
{
return H;
}
void setL(int l)
{
L = l;
}
void setW(int w)
{
W = w;
}
void setH(int h)
{
H = h;
}
// 判断两个立方体是否相等
bool compare_cube(Cube &c1)
{
return c1.getL() == L && c1.getW() == W && c1.getH() == H;
}
private:
int L;
int W;
int H;
};
bool compare_cube(Cube &c1, Cube &c2) // 这里的 & 是引用
{
return c1.getL() == c2.getL() && c1.getW() == c2.getW() && c1.getH() == c2.getH();
}
void test02()
{
Cube c1;
c1.setL(120);
c1.setW(20);
c1.setH(30);
Cube c2;
c2.setL(10);
c2.setW(20);
c2.setH(30);
if(c1.compare_cube(c2))
{
cout << "==" <<endl;
}
else
{
cout << "!=" <<endl;
}
if(compare_cube(c1, c2))
{
cout << "==" <<endl;
}
else
{
cout << "!=" <<endl;
}
}
int main()
{
test02();
return 0;
}