您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
1、
#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(void)
{
//通过栈的方法实例化对象
Coordinate coor;
coor.x=100;
coor.y=200;
coor.printx();
coor.printy();
//从堆实例化对象
Coordinate *p=new Coordinate();
if(p==NULL)//判断有木有申请内存成功
{
return 0;
}
p->x=234;
p->y=300;
p->printx();
p->printy();
delete p;//释放内存
p=NULL;//p置空
system("pause");
return 0;
}运行结果:

2、字符串的使用方法:

#include <iostream>
#include<stdlib.h>
#include<string>//字符串及其相关函数包含 必须加 否则无法识别相关函数
using namespace std;
int main(void)
{
string name;//一个字符串变量
cout<<"please input your name "<<endl;//提示输入
getline(cin,name);//字符串输入函数
if(name.empty())//name.empty()若字符串为空,则返回值为1,反之为0
{
cout<<"input is NULL..."<<endl;
system("pause");
return 0;
}
if(name=="imooc")
{
cout<<"you are the adminstrator "<<endl;
}
cout <<"hello"+name<<endl;//字符串常量连接形式:常量+变量
cout<<"your name length:"<<name.size()<<endl;
cout<<"your name first letter is:"<<name[0]<<endl;//name[0]首字母
system("pause");
return 0;
}运行结果
:
3、小练习
#include <iostream>
#include<stdlib.h>
#include <string>
using namespace std;
/**
* 定义类:Student
* 数据成员:名字、年龄
*/
class student
{
public:
string m_strName;//定义数据成员名字 m_strName 和年龄 m_iAge
int m_iAge;
};
int main()
{
student stu;//Student对象stu
// 设置对象的数据成员
stu.m_strName = "慕课网";//从栈实例化对象
stu.m_iAge = 2;
// 通过cout打印stu对象的数据成员
cout << stu.m_strName << " " << stu.m_iAge<< endl;
system("pause");
return 0;
}运行结果:

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。