类
struct、class定义类
先看一下如何定义struct、class的类
可以注意到我们这里只调用了struct类型的类,而没有调用class类型的类,原因是struct默认的成员是public的,
class默认的成员是private的。
private限制的成员不能被外部访问(但是类内部没有问题),而public可以所以我们这样写,来public class类。
#include <iostream>
using namespace std;
struct apple
{ //成员变量,描述类的属性,例如苹果的颜色,苹果的味道
string color;
string taste;
//成员函数,即类的方法,(能做什么)例如,可以被吃
void eat(){
cout<<"the "<<color<<" and "<<taste<<" apple can be eat"<<endl;
}
};
class pear{
string color;
string taste;
void eat(){
cout<<"the "<<color<<" and "<<taste<<" pear can be eat"<<endl;
}
};
int main(int argc, char *argv[])
{ struct apple apple1;
apple1.color="red";
apple1.taste="sweet";
apple1.eat();
struct apple apple2;
apple2.color="green";
apple2.taste="sour";
apple2.eat();
class pear pear1;
return 0;
}
然后我们用指针访问一下类中的成员,用->符号就可以了
#include <iostream>
using namespace std;
class pear{
public:
string color;
string taste;
void eat(){
cout<<"the "<<color<<" and "<<taste<<" pear can be eat"<<endl;
}
};
int main(int argc, char *argv[])
{ class pear pear1;
class pear *ppear1=&pear1;
ppear1->color="yellow";
ppear1->taste="sweet";
ppear1->eat();
class pear pear2;
class pear *ppear2=&pear2;
ppear2->color="green";
ppear2->taste="bitter";
ppear2->eat();
return 0;
}
C++ class和struct到底有什么区别
C++ 中保留了C语言的 struct 关键字,并且加以扩充。在C语言中,struct 只能包含成员变量,不能包含成员函数。而在C++中,struct 类似于 class,既可以包含成员变量,又可以包含成员函数。
C++中的 struct 和 class 基本是通用的,唯有几个细节不同:
- 使用 class 时,类中的成员默认都是 private 属性的;而使用 struct 时,结构体中的成员默认都是 public 属性的。
- class 继承默认是 private 继承,而 struct 继承默认是 public 继承(《C++继承与派生》一章会讲解继承)。
- class 可以使用模板,而 struct 不能(《模板、字符串和异常》一章会讲解模板)。
C++ 没有抛弃C语言中的 struct 关键字,其意义就在于给C语言程序开发人员有一个归属感,并且能让C++编译器兼容以前用C语言开发出来的项目。
在编写C++代码时,我强烈建议使用 class 来定义类,而使用 struct 来定义结构体,这样做语义更加明确。
使用 struct 来定义类的一个反面教材:
- #include <iostream>
- using namespace std;
- struct Student{
- Student(char *name, int age, float score);
- void show();
- char *m_name;
- int m_age;
- float m_score;
- };
- Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }
- void Student::show(){
- cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
- }
- int main(){
- Student stu("小明", 15, 92.5f);
- stu.show();
- Student *pstu = new Student("李华", 16, 96);
- pstu -> show();
- return 0;
- }
运行结果:
小明的年龄是15,成绩是92.5
李华的年龄是16,成绩是96
这段代码可以通过编译,说明 struct 默认的成员都是 public 属性的,否则不能通过对象访问成员函数。如果将 struct 关键字替换为 class,那么就会编译报错。
若有收获,就点个赞吧