Lane
面向对象程序设计

面向对象程序设计

C++的介绍

the first c++ programme

1
2
3
4
5
6
7
8
9
# include <iostream>
using namespace std;

int main()
{
cout <<"Hello,World! I am "<< 18
<<" Today!"<< endl;//endl理解为回车
return 0;
}

read input

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
{
cout << "Please enter your age: ";
int age;
cin >> age;
cout << "Hello ,World! I am" << age <<" years old!"<< endl;
return 0;
}

Using Objects

The string class

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 <string>
//定义string变量
string str;
//初始化
string str = "Hello";
//读和写
cin >> str;
cout << str;
//assignment
char cstr1[20];
char cstr2[20]="jaguar";
string str1;
string str2= "panther";
cstr1=cstr2;//非法
str1= str2; //合法
//Concatenation
string str3;
str3= str1+ str2;
str1+=str2;
str1+= "a string literal";
// constructors(Ctors)
string (const char *cp, int len);
string (const string& s2, int pos);
string (const string& s2, int pos ,int len);
// sub-string
substr(int pos ,int len);
//Modification
assign(...);
insert(...);
insert(int pos,const string& s);
erase(...);
append(...);
replace(...);
replace (int pos, int len,const string& s);
//search
find (const string& s);

string class 的应用

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
#include <iostream>
#include <string>
using namespace std;

int main()
{
string str1="foo";
string str2="bar";
string str3=str1+str2;
cout <<"str3 = "<<str3 <<endl;
str2+=str1;
cout <<"str2 = "<<str2 << endl;

str3 = "hello, china!";
string str4("hello, zju!");
string str5(str3);
string str6(str3, 7, 5);
cout <<"str4 = "<<str4 <<endl;
cout <<"str5 = "<<str5 <<endl;
cout <<"str6 = "<<str6 <<endl;

string str7 =str3.substr(7,5);
cout <<"str7 = " << str7 << endl;
string str8 = str3;
str8.replace(7,5,"hangzhou");
cout <<"str8 = "<< str8 <<endl;

str8.assign(10, 'A');
cout <<"str8 = "<< str8 <<endl;

string str9 = "hello, hangzhou city";
cout << "str9 = " << str9 << endl;
string str_to_find = "hangzhou";
cout << str9.find(str_to_find) << endl;
str9.replace(str9.find(str_to_find),str_to_find.length(),"beijing");
cout <<"str9 = "<< str9 <<endl;
}

File I/O

1
2
3
4
5
6
7
8
9
#include <ifstream> //read from file
#include <ofstream> //write to file

ofstream File1("C:\\test.txt");
File1 << "Hello world" << std::endl;

ifstream File2("C:\\test.txt");
std::string str;
File2 >> str;

I/O example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
string str1= "foo, bar!";
ofstream fout("out.txt");
fout << str1 << endl;

ifstream fin("out.txt");
string str2, str3;
fin >> str2 >> str3;
cout << "str2= " << str2 << endl;
cout << "str3= " << str3 << endl;
}
本文作者:Lane
本文链接:https://lakerswillwin.github.io/2025/01/14/oop/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可