溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

對(duì)象實(shí)例化、字符串的使用方法

發(fā)布時(shí)間:2020-10-11 09:19:53 來(lái)源:網(wǎng)絡(luò) 閱讀:464 作者:lillian_trip 欄目:編程語(yǔ)言

1、

#include <iostream>
#include<stdlib.h>
using namespace std;
class Coordinate//類(lèi)定義 類(lèi)名
{  public://公共。公開(kāi)
int x;
int y;
  void printx()
  {
	  cout<<x<<endl;
  }
  void printy()
  {
	  cout<<y<<endl;
  }
};
int main(void)
{  
	//通過(guò)棧的方法實(shí)例化對(duì)象
	Coordinate coor;
	coor.x=100;
	coor.y=200;
	coor.printx();
	coor.printy();
	//從堆實(shí)例化對(duì)象
	Coordinate *p=new Coordinate();
		if(p==NULL)//判斷有木有申請(qǐng)內(nèi)存成功
		{
		return 0;
		}
	p->x=234; 
	p->y=300;
	p->printx();
	p->printy();
	delete p;//釋放內(nèi)存
	p=NULL;//p置空
	system("pause");
        return 0;
}

運(yùn)行結(jié)果:

對(duì)象實(shí)例化、字符串的使用方法

2、字符串的使用方法:

對(duì)象實(shí)例化、字符串的使用方法

#include <iostream>
#include<stdlib.h>
#include<string>//字符串及其相關(guān)函數(shù)包含 必須加  否則無(wú)法識(shí)別相關(guān)函數(shù)
using namespace std;
int main(void)
{  
string name;//一個(gè)字符串變量
cout<<"please input your name "<<endl;//提示輸入
    getline(cin,name);//字符串輸入函數(shù)
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;
}

運(yùn)行結(jié)果

對(duì)象實(shí)例化、字符串的使用方法

3、小練習(xí)

#include <iostream>
#include<stdlib.h>
#include <string>
using namespace std;

/**
  * 定義類(lèi):Student
  * 數(shù)據(jù)成員:名字、年齡
  */
class student
{
public:
    string m_strName;//定義數(shù)據(jù)成員名字 m_strName 和年齡 m_iAge
    int  m_iAge;
    
};

int main()
{
    student stu;//Student對(duì)象stu
    
    // 設(shè)置對(duì)象的數(shù)據(jù)成員
    stu.m_strName = "慕課網(wǎng)";//從棧實(shí)例化對(duì)象
    stu.m_iAge = 2;
    
    // 通過(guò)cout打印stu對(duì)象的數(shù)據(jù)成員
    cout << stu.m_strName << " " << stu.m_iAge<< endl;
	system("pause");
    return 0;
}

運(yùn)行結(jié)果:

對(duì)象實(shí)例化、字符串的使用方法


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI