您的位置:首页 > 编程语言 > C语言/C++

C++学习的第二天

2018-03-23 13:23 841 查看
在学习C++的第二天中,我通过写一些代码加深了对C++对象的认识以及它和C的区别。

#include <stdio.h>
#include<iostream>
using namespace std;
class DEMO
{
public:
char ch;
int n;
float f;
void fun()
{
cout << "ch = " << ch << ",n = " << n << ",f = " << f << endl;
}
};
int main(int argc, char **argv)
{
DEMO demo;
DEMO *p;
demo.ch = 'h';
demo.n = 88;
demo.f = 99.5;
demo.fun();
p = &demo;
p -> ch = 'z';
p -> n = 99;
p -> f = 96.98;
p -> fun();

return 0;
}


#include <stdio.h>
#include<iostream>
using namespace std;
class Circle
{
private:
int m_r;
int m_c;
int m_s;
public:
void Set_R(int r)
{
m_r = r;
}
int Get_C()
{
return m_r*3*2;
}
int Get_S()
{
return m_r*m_r*3;
}
};
void fun(Circle c)
{
cout << "C = " << c.Get_C() << endl;
cout << "S = " << c.Get_S() << endl;
}
void fun1(Circle *c)
{
cout << "C = " << c -> Get_C() << endl;
cout << "S = " << c -> Get_S() << endl;
}
void fun2(Circle &c)
{
cout << "C = " << c.Get_C() << endl;
cout << "S = " << c.Get_S() << endl;
}
int main(int argc, char **argv)
{
Circle c;
c.Set_R(10);
fun(c);
fun1(&c);
fun2(c);

return 0;
}


#include <stdio.h>
#include<iostream>
using namespace std;
class Point
{
private:
int m_x;
int m_y;
public:
Point();
Point(int x);
Point(int x,int y);
Point(P
4000
oint &p);
~Point();
int GetX();
int GetY();
};
Point::Point()
{
cout << "point constructor!\n";
m_x = 1;
m_y = 2;
}
Point::Point(int x)
{
m_x = x;
m_y = 3;
}
Point::Point(int x,int y)
{
m_x = x;
m_y = y;
}
Point::Point(Point &p)
{
m_x = p.m_x;
m_y = p.m_y;
}
Point::~Point()
{
cout << "point destruct!\n";
}
int Point::GetX()
{
return m_x;

}
int Point::GetY()
{
return m_y;
}
int main(int argc, char **argv)
{
Point p1;
cout << "p1.x = " << p1.GetX() << " p1.y = " << p1.GetY() << endl;
Point p2(2);
cout << "p2.x = " << p2.GetX() << " p2.y = " << p2.GetY() << endl;
Point p3(3,4);
cout << "p3.x = " << p3.GetX() << " p3.y = " << p3.GetY() << endl;
Point p4(p3);
cout << "p4.x = " << p4.GetX() << " p4.y = " << p4.GetY() << endl;

return 0;
}


另外还学会了对代码进行分装,即用几个文件分别对应代码中的每个模块。

比如我要判断点是否在圆内或者圆外,我需要建立5个文件:点的定义文件,点的函数文件,圆的定义文件,圆的函数文件,主函数文件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: