对象实例化
从堆中申请的内存,记得释放。
*************************************************************
***************************************************************************
#include <stdlib.h>
#include <iostream>
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 = 10;
coor.y = 20;
coor.printX();
coor.printY();
Coordinate *p = new Coordinate();//堆申请
if(NULL == p)
{
cout << "new error" << endl;
return 0;
}
p->x = 15;
p->y = 25;
p->printX();
p->printY();
delete p;
p = NULL;
system("pause");
return 0;
}
**************************************************************
String
********************************************
题目:
1.提示用户输入姓名
2.接收用户输入
3.向用户问好,hello,xx
4.告诉用户长度
5.用户首字母
6.如果用户直接回车,告诉用户为空
7.如果输入的是michael,告诉是个admin
/************************************************************
/*题目:
1.提示用户输入姓名
2.接收用户输入
3.向用户问好,hello,xx
4.告诉用户长度
5.用户首字母
6.如果用户直接回车,告诉用户为空
7.如果输入的是michael,告诉是个admin
****************************************************************/
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string name;
cout << "Input you name" << endl;
getline(cin, name);
if(name.empty())
{
cout << "input is null.." << endl;
system("pause");
return 0;
}
if (name == "michael")
{
cout << "You are the admin" << endl;
}
cout << "hello " + name << endl;
cout << "You name length:" << name.length() << endl;
cout << "You name first letter is:" << name[0] << endl;
system("pause");
return 0;
}
string IO 操作:getline。
这个函数接受两个参数:一个输入流对象和一个 string 对象。getline 函数从输入流的下一行读取,并保存读取的内容到不包括换行符。和输入操作符不一样的是,getline 并不忽略行开头的换行符。只要 getline 遇到换行符,即便它是输入的第一个字符,getline 也将停止读入并返回。如果第一个字符就是换行符,则 string 参数将被置为空 string。
当进行 string 对象和字符串字面值混合连接操作时,+ 操作符的左右操作数必须至少有一个是 string 类型的:
string s1 = "hello"; // no punctuation
string s2 = "world";
string s3 = s1 + ", "; // ok: adding a string and a literal
string s4 = "hello" + ", "; // error: no string operand
string s5 = s1 + ", " + "world"; // ok: each + has string operand
string s6 = "hello" + ", " + s2; // error: can't add string literals
输入为空