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;
}