赞
踩
目录
在 C++中,类(Class)是一种用户自定义的数据类型,它用于描述具有相似属性和行为的对象。
类定义了对象的属性(成员变量)和行为(成员函数)。
对象(Object)是类的实例,它是根据类的定义创建的具体实体。
在 C++中,不使用 new
直接声明对象和使用 new
动态分配内存创建对象有以下一些区别:
new
是在栈上分配内存,而使用 new
是在堆上分配内存。delete
释放。以下是一个示例代码,展示了使用 new
和不使用 new
的区别:
- // 不使用 new
- 猫 小红; // 在栈上创建对象
-
- // 使用 new
- 猫 *小红指针 = new 猫; // 在堆上创建对象
C++ 中的访问修饰符用于控制类成员(包括成员变量和成员函数)的访问权限。常见的访问修饰符有:
以下是一个示例代码,展示了不同访问修饰符的使用:
- class Student {
- public: //公开
- void setName(const std::string& name) { m_name = name; }
-
- protected: //保护
- std::string m_name;
-
- private: //私有
- int m_age;
- };
调用:
示例代码:
- class Student {
- public:
- Student() {
- std::cout << "Default constructor called." << std::endl;
- }
- };
代码
- #include<iostream>
- #include<vector>
- #include <string>
-
-
- class Student {
- public: //公开
- Student(std::string name) {
- m_age = 18;
- m_name = name;
- }
- void getName() {
- std::cout << "名字"<< m_name <<std::endl;
- std::cout << "年龄" << m_age << std::endl;
- }
-
- protected: //保护
- std::string m_name;
-
- private: //私有
- int m_age;
- };
-
- int main() {
-
- Student student("xiao hong");
- student.getName();
-
-
- return 0;
- }

在对象销毁时被调用。
用于释放资源或进行其他清理工作。
示例代码:
- class Student {
- public:
- ~Student() {
- std::cout << "销毁" << std::endl;
- }
- };
代码
- #include<iostream>
- #include<vector>
- #include <string>
-
-
- class Student {
- public: //公开
- Student() {
- std::cout << "开始创建" << std::endl;
- std::cout << "构造函数" << std::endl;
- }
- ~Student() {
- std::cout << "销毁" << std::endl;
- std::cout << "析构函数" << std::endl;
- }
- };
-
- int main() {
-
- // Student student ("xiao hong");
- Student* student = new Student();
- delete(student);
-
-
- return 0;
- }

代码:
- #include<iostream>
- #include<vector>
- #include <string>
-
-
- class Student {
- public: //公开
- std::string m_name;
- Student() {
- std::cout << "开始创建" << std::endl;
- std::cout << "构造函数" << std::endl;
- m_age = 18;
- }
- ~Student() {
- std::cout << "销毁" << std::endl;
- std::cout << "析构函数" << std::endl;
- }
-
- void GetName() {
- std::cout << "名字" << m_name << std::endl;
- std::cout << "年龄" << m_age << std::endl;
- }
-
- private:
- int m_age;
- };
-
- int main() {
-
- // Student student ("xiao hong");
- Student* student = new Student ;
- student->m_name = "xiao hong";
- student->GetName();
-
- delete(student);
-
-
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。