一、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
二、字符串的使用方法:函数
#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
三、小练习对象
#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