對象實例化、字符串的使用方法

一、ios

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

運行結果:ide

wKioL1mnWWSStLg5AAANmlwd5a0194.png

二、字符串的使用方法:函數

wKiom1moI_WweWSiAAEMtUILAQI735.png

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

運行結果spa

wKioL1moI8Phaw7dAAAX8yCl0-Y491.png3d

三、小練習對象

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

運行結果:blog

wKioL1mpFYjT1BcOAAAJT0wO6qA665.png

相關文章
相關標籤/搜索