C++类和对象001

12 篇文章 0 订阅
10 篇文章 0 订阅

C++类和对象001

  • 类的定义

#include <iostream>
#include <string>

using namespace std;

/* 类 */
class stu {
    // 变量 : 属性
    string name;
    int age;
    
    // 函数 : 行为 | 动作
    void coding() {
        
    }
    void run() {
        
    }
}

  • 对象的创建

#include <iostream>
#include <string>

using namespace std;

/* 类 */
class stu {
    // 变量 : 属性
    string name;
    int age;
    
    // 函数 : 行为 | 动作
    void coding() {
        
    }
}

int main() {
	int age;
    
    // 1. 栈内存创建对象
    // 复合类型 s : 对象
    stu s;
    // stu s0();	// 不是创建对象,其实就是声明一个函数原型。s0是函数名,stu是函数返回值类型,函数没有参数。
    
    // 2.在堆里面创建
    stu *s1 = new stu;
    stu *s2 = new stu();	// _init_(self, name, age)
    
    return 0;
}

  • 访问对象中的成员

#include <iostream>
#include <string>

using namespace std;

/* 类 */
class stu {
    // 变量 : 属性
    string name;
    int age;
    
    // 函数 : 行为 | 动作
    void coding() {
         cout<< age << " 岁的 " << name << "在看敲代码" <<endl;
    }
    void run() {
        cout<< age << " 岁的 " << name << "在跑步" <<endl;
    }
}

int main() {
    // 1. 栈内存 对象.成员 方式来调用
    stu s;
    s.name = "张三";
    s.age = 18;
    s.run();
    s.read();
    
    cout << "************************" << endl;
    
    // 2. 堆内存
    stu * s2 = new stu;
    
    // 方式一:先解引用,再使用 对象.成员 的方式访问
    (*s2).name = "李四";
    (*s2).age = 19;
    (*s2).run();
    (*s2).read();
    
    // 方式二:使用箭头的方式来访问成员 指针->成员
    s2->name = "王五";
    s2->age = 20;
    s2->run();
    s2->read();
    
    return 0;
}
  • 访问修饰符

private :私有成员,私有成员只能再类里面访问。

public :公有成员,可以在类里面访问,也可以再类的外面访问。

protected :受保护的,主要是针对子类。

#include <iostream>
#include <string>

using  namespace std;


class stu {
protected:
    string name;
    int age;
    
    void run() {
        cout << age << " 岁的 " << name << " 在跑步。" << endl;
    }
    void read() {
        cout << age << " 岁的 " << name << " 在看《哈利波特》。" << endl;
    }
}

int main() {
    stu s;
    // s1.age = 12; // error: 'int stu::age' is protected
    
    return 0;
}
  • 在类的外面实现类当中的成员函数

在开发中采用分离式写法,类在头部文件中声明,在源文件中实现它的成员函数。

#include <iostream>
#include <string>

using namespace std;

class stu {
public:
    string name;
    int age;
    
    // 函数的原型。
    void coding();
}

// 在外部实现类当中的成员函数
// 在函数名称前面加上 类名:: 就可以表示该函数就是类当中的成员函数的具体实现
void stu::coding() {
    cout << name << " 在敲代码" << endl;
}

int main() {
    stu s;
    s.name = "张三";
    s.age = 18;
    s.coding();
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值