C++中的结构体不仅可以包含不同类型的数据,而且还可以包含操作这些数据的函数。
#include <iostream>
using namespace std;
struct Complex{
double i;
double r;
void init(double rr, double ii){
r = rr;
i = ii;
}
double real() {
return r;
}
double image() {
return i;
}
};
int main(void) {
Complex c;
c.init(2,3);
cout << c.real() << " + " << c.image() << "i" << endl;
return 0;
}
将数据和操作数据的函数包装在一起的主要目的就是实现的封装和隐藏。隐藏就是不让结构外的函数直接修改数据结构中的数据,只能通过结构体的成员函数对数据进行修改。但上面的代码明显没有做到这一点。为此C++中新增了3个访问权限限定符,用于设置结构体中数据成员和函数成员的访问权限
public
公有成员(函数、数据),可被任何函数访问(结构体内和结构体外)。
protected
保护成员,与集成相关
private
私有成员(函数、数据),只能被结构体内函数访问
#include <iostream>
using namespace std;
struct Complex{
private:
double i;
double r;
void init(double rr, double ii){
r = rr;
i = ii;
}
public:
double real() {
return r;
}
double image() {
return i;
}
void ret_i(double data_r, double data_i){
init(data_r, data_i);
}
};
int main(void) {
Complex c;
// c.init(2,3); //init() 函数是私有成员
c.ret_i(5,3); //通过公共成员访问私有成员
cout << c.real() << " + " << c.image() << "i" << endl;
return 0;
}
struct 还是容易和传统C语言中的结构混淆,C++中引进了功能与struct相同,但更安全的数据类型:类。
更安全是指结构体将所有成员都默认为public(公共),不够安全;类中成员默认为private(私有)权限
//语法格式
class 类名{
private:
成员数据;
成员函数;
public:
成员数据;
成员函数;
protected:
成员数据;
成员函数;
}; //特别注意,别忘了!!!!!!!!!!!
#include <iostream>
using namespace std;
class Student{
private:
string m_name;
int m_age;
int m_no;
public:
/*类内声明*/
void set_name(const string &name);
void set_age(int age);
void set_no(int no);
void eat(const string &food);
void who();
};
/*类外定义*/
void Student::set_name(const string &name){
m_name = name;
}
void Student::set_age(int age) {
m_age = age;
}
void Student::set_no(int no){
m_no = no;
}
void Student::eat(const string &food){
cout << "我今天吃了" << food << endl;
}
void Student::who() {
cout << "我叫: " << m_name << " 今年: " << m_age << " 学号: " << m_no << endl;
}
/*初始化函数*/
void init(Student &s1, const string &init_name, int init_age, int init_no, const string &food) {
s1.set_name(init_name);
s1.set_age(init_age);
s1.set_no(init_no);
s1.who();
s1.eat(food);
}
int main(void) {
Student s1;
init(s1, "王钢蛋", 18, 24020, "炸鸡");
init(s1, "刘铁锤", 20, 24031, "汉堡");
return 0;
}