本文一些代码的形式演示c++语言的特性,关于环境的搭建可以参考 设置 Windows 下的GCC开发环境
- 代码: 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(); }
|
- 代码: 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(); }
|
- 代码 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(); }
|
- 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(); }
|
- 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(); }
|
- 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); }
|