C++语言特性演示 - 类与对象

本文一些代码的形式演示c++语言的特性,关于环境的搭建可以参考 设置 Windows 下的GCC开发环境

  1. 代码: c1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<bits/stdc++.h>  
using namespace std;

class Cpoint {
private:
int X,Y;
public:
void print() {
cout<<X<<Y;
}
void set(int x,int y) {
X=x;
Y=y;
}
};

int main() {
Cpoint p1,p2;
p1.set(3,5);
p2.set(8,10);
p1.print();
p2.print();
}
  1. 代码: c2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Cpoint {
private:
int X,Y;
public:
Cpoint(int a, int b) {
X = a;
Y = b;
}
void print() {
cout<<X<<Y;
}
void set(int x,int y) {
X=x;
Y=y;
}
};

int main() {
Cpoint p1(1,10);
p1.print();
}
  1. 代码 c3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<bits/stdc++.h>  
using namespace std;

class Cpoint {
private:
int X,Y;
public:
Cpoint() {
this->X = 10;
this->Y = 20;
}
void print() {
cout<<X<<Y;
}
};

int main() {
Cpoint p1;
p1.print();
}
  1. c4.cpp
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
#include<bits/stdc++.h>  
using namespace std;

class Cpoint {
private:
int X,Y;
public:
Cpoint(int a, int b) {
this->X = a;
this->Y = b;
}

void print() {
cout<<X<<Y;
}
Cpoint(Cpoint &p){
X=p.X;
Y=p.Y;
cout<<"copy initialization called.\n";
}
~Cpoint() {
cout<<"destructor called\n";
}

};

int main() {
Cpoint p1(5,7);
Cpoint p2(p1);
p2.print();
}
  1. c4.cpp
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
40
41
42
43
44
45
46
47
#include<bits/stdc++.h>  
using namespace std;

class Cpoint {
private:
int X,Y;
public:
Cpoint(int a, int b) {
this->X = a;
this->Y = b;
}

void print() {
cout<<X<<Y;
}
Cpoint(Cpoint &p){
X=p.X;
Y=p.Y;
cout<<"copy initialization called.\n";
}
~Cpoint() {
cout<<"destructor called\n";
}

};

class Cpoint1: public Cpoint {
private:
int Z;
public:
Cpoint1(int a, int b, int c): Cpoint(a, b) {
Z = c;
}

void print1() {
cout<<Z;
}
void set1(int z) {
Z=z;
}
};

int main() {
Cpoint1 p1(10, 20, 30);
p1.print();
p1.print1();
}
  1. c6.cpp
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
#include<bits/stdc++.h>  
using namespace std;

class point {
int x,y;
public:
point(int x1,int y1) {
x=x1;
y=y1;
}
virtual int area() {
return 0;
}
};

class rect:public point {
int l,w;
public:
rect(int x1,int y1,int l1,int w1): point(x1,y1) {
l=l1;
w=w1;
}
int area() {
return l * w;
}
};


void fun(point &p) {
cout<<p.area()<<endl;
}

int main() {
point p(10, 10);
fun(p);
rect rec(2,4,10,6);
fun(rec);
}

本文标题:C++语言特性演示 - 类与对象

文章作者:Morning Star

发布时间:2019年11月15日 - 10:11

最后更新:2021年04月16日 - 15:04

原始链接:https://www.mls-tech.info/cplus/cplus-basic-class/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。