文章目录
结构体
- C++中的结构体不仅可以包含不同类型的数据,而且还可以包含操作这些数据的函数
cpp
#include <iostream>
using namespace std;
struct Complex{
double r ; //实部
double i; //虚部
void init(double rr, double ii){
r = rr;
i = ii;
}
double real(){
return r;
}
double image(){
return i;
}
};
int main(void){
Complex a;
a.init(2,3);
cout << a.real() << " + " << a.image() << "i" << endl;
return 0;
}
- 将数据和操作数据的函数包装在一起的主要目的就是实现的封装和隐藏。隐藏就是不让结构体外的函数直接修改数据结构中的数据,只能通过结构的成员函数对数据进行修改。但上面的代码显然没能做到这一点。为此C++中新增了3个访问权限限定符,用于设置结构体中数据成员和函数成员的访问权限:
- public
- 公有成员(函数、数据), 可被任何函数访问(结构体内和结构体外)
- protected
- 保护成员, 与继承相关
- private
- 私有成员(函数、数据),只能被结构体内部函数访问
cpp
#include <iostream>
using namespace std;
struct Complex{
private:
double r ; //实部
double i; //虚部
public:
void init(double rr, double ii){
r = rr;
i = ii;
}
double real(){
return r;
}
double image(){
return i;
}
void set_real(double data){
r = data;
}
void set_image(double data){
i = data;
}
};
int main(void){
Complex a;
a.init(2,3);
//a.r = 8;
a.set_real(8);
cout << a.real() << " + " << a.image() << "i" << endl;
return 0;
}
类
- struct还是容易和传统C语言中的结构混淆,C++中引进了功能与struct相同,但更安全的数据类型:类
- 更安全是指结构体将所有成员都默认为public,不够安全;类中成员默认为private权限
- 语法格式
cpp
class 类名{
private:
成员数据;
成员函数;
public:
成员数据;
成员函数;
protected:
成员数据;
成员函数;
}; //特别注意;不要忘了
cpp
#include <iostream>
using namespace std;
//struct Complex{
class Complex{
private:
double r ; //实部
double i; //虚部
public:
void init(double rr, double ii){
r = rr;
i = ii;
}
double real(){
return r;
}
double image(){
return i;
}
void set_real(double data){
r = data;
}
void set_image(double data){
i = data;
}
};
int main(void){
Complex a;
a.init(2,3);
//a.r = 8;
a.set_real(8);
cout << a.real() << " + " << a.image() << "i" << endl;
return 0;
}
cpp
#include <iostream>
using namespace std;
class Student{
private:
string m_name;
int m_age;
int m_no;
public:
void setName(const string& name){
m_name = name;
}
void setAge(int age){
if(age < 0)
cout << "无效年龄" << endl;
else
m_age = age;
}
void setNo(int no){
m_no = no;
}
void sleep(int hour){
cout << "我睡了"<< hour <<"小时"<< endl;
}
void eat(const string &food){
cout << "我正在吃" <<food << endl;
}
void learn(const string &course){
cout << "我正在学习" << course << endl;
}
void who(){
cout << "我叫: "<<m_name << ", 我今年" << m_age << endl;
}
};
int main(void){
Student s1;
s1.setName("张飞");
s1.setAge(21);
s1.setNo(10003);
s1.who();
s1.eat("烧烤");
Student s2;
s2.setName("刘备");
s2.setAge(28);
s2.setNo(10000);
s2.who();
s2.learn("C++");
return 0;
}