对象实例化、字符串的使用方法

1、

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#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;
}

运行结果:

wKioL1mnWWSStLg5AAANmlwd5a0194.png

2、字符串的使用方法:

wKiom1moI_WweWSiAAEMtUILAQI735.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#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;
}

运行结果

wKioL1moI8Phaw7dAAAX8yCl0-Y491.png

3、小练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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;
}

运行结果:

wKioL1mpFYjT1BcOAAAJT0wO6qA665.png


本文转自 lillian_trip 51CTO博客,原文链接:http://blog.51cto.com/xiaoqiaoya/1961266,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值