0、类的定义与调用(堆、栈)
代码;
#include <iostream>
#include <stdlib.h>
using namespace std;
//类名最好能看出类的功能
class Coordinate{
public:
int x;
int y;
void printX(){
cout<<x<<endl;
}
void printY(){
cout<<y<<endl;
}
};
int main(){
Coordinate coor;//定义类的名称(使用栈),系统自动回收空间
coor.x = 10;
coor.y = 20;
coor.printX();
coor.printY();
Coordinate *p = new Coordinate;//(使用堆),要手动释放空间
if(NULL == p){//堆可能申请不成功,要判断是否为NULL
//failed
return 0;
}
p->x = 100;
p->y = 200;
p->printX();
p->printY();
//要释放p
delete p;
p = NULL;
system("pause");
return 0;
}
1、string的几种定义
代码:
//string
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(){
string s1 = "hello";
string s2("world");
string s3 = s1 + s2;
string s4 = "hello" + s2;
string s5 = "hello" + s2 + "world";
//不合法
//string s6 = "hello" + "world";
cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;
cout<<s4<<endl;
cout<<s5<<endl;
//cout<<s6<<endl;
}
2、字符串的基本使用:
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(){
string name;
cout<<"请输入您的名字:";
getline(cin,name);
if(name.empty()){
cout<<"输入为空"<<endl;
system("pause");
return 0;
}
if(name == "imooc"){
cout<<"you are a administor"<<endl;
}
cout<<"hello " + name<<endl;
//不能用 cout<<"your name length is:" + name.size()<<endl;这种方式,因为是不同类型
cout<<"your name length is:"<<name.size()<<endl;
cout<<"your name first letter is:"<<name[0]<<endl;
system("pause");
return 0;
}
3、封装代码演示
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
//注意类中对象的命名规则
class Student{
public:
void setName(string _name){
m_strName = _name;
}
string getName(){
return m_strName;
}
void setGender(string _gender){
m_strGender = _gender;
}
string getGender(){
return m_strGender;
}
int getScore(){
return m_iScore;
}
//初始化分数
void initScore(){
m_iScore = 0;
}
void study(int _score){
m_iScore += _score;//m_iScore = m_iScore + _score
}
private:
string m_strName;
string m_strGender;
int m_iScore;
};
int main(){
Student stu;
stu.initScore();
stu.setName("zhangsan");
stu.setGender("女");
stu.study(5);
stu.study(3);
cout<<stu.getName()<<" "<<stu.getGender()<<" "<<stu.getScore()<<endl;
system("pause");
}
4、关于封装的小练习
emmm感觉封装确实不错,比较严谨的感觉
#include <iostream>
#include <string>
using namespace std;
/**
* 定义类:Student
* 数据成员:m_strName
* 数据成员的封装函数:setName()、getName()
*/
class Student
{
public:
// 定义数据成员封装函数setName()
void setName(string _name){
m_strName = _name;
}
// 定义数据成员封装函数getName()
string getName(){
return m_strName;
}
//定义Student类私有数据成员m_strName
private:
string m_strName;
};
int main()
{
// 使用new关键字,实例化对象
Student *str = new Student;
// 设置对象的数据成员
str->setName("慕课网");
// 使用cout打印对象str的数据成员
cout<<str->getName()<<endl;
// 将对象str的内存释放,并将其置空
delete str;
str = NULL;
return 0;
}