这几天一直在写网络编程,感觉有点枯燥,今天在看了半个小时的网络后,开始看c++。因为学过c的缘故,c++上手的时候感觉不怎么难,比较容易理解,前面几章看的比较快,在看到构造函数和析构函数、共有结点与友元还有单继承和多继承的时候,感觉就有点吃力了。在理解了几个程序后,大概也理解了60%吧。
1、带参数的构造函数
/*********************************************************************
File Name: gouzao.cpp
Author: date:
Description:
Fuction List:
********************************************************************/
#include <iostream>
#include <string.h>
using namespace std;
class Cshose
{
public:
Cshose();
Cshose(int s, char* strcolor);
~Cshose();
int getsize();
char* getcolor();
private:
int size;
char color[10];
};
Cshose::Cshose()
{
size = 40;
strcpy(color, "红色");
}
Cshose::Cshose(int s, char* strcolor)
{
size = 40;
strcpy(color, strcolor);
}
int Cshose::getsize()
{
return size;
}
char* Cshose::getcolor()
{
return color;
}
Cshose::~Cshose()
{
cout<<"销毁对象!"<<endl;
}
int main()
{
Cshose shose1;
Cshose shose2(38,"白色");
cout<<"休闲鞋的尺寸为:"<<shose1.getsize()<<"\t颜色为:"<<shose1.getcolor()<<endl;
cout<<"休闲鞋的尺寸为:"<<shose2.getsize()<<"\t颜色为:"<<shose2.getcolor()<<endl;
return 0;
}
#include <iostream>
using namespace std;
class Cpoint
{
public:
Cpoint();
Cpoint(int x, int y);
void disp();
void getxy(int &x, int &y);
private:
int m_x;
int m_y;
};
Cpoint::Cpoint()
{
m_x = 0;
m_y = 0;
cout<<"调用Cpoint默认构造函数"<<endl;
}
Cpoint::Cpoint(int x, int y)
{
m_x = x;
m_y = y;
cout<<"调用Cpoint构造函数"<<endl;
}
void Cpoint::getxy(int &x, int &y)
{
x = m_x;
y = m_y;
}
void Cpoint::disp()
{
cout<<m_x<<","<<m_y<<endl;
}
class C3point:public Cpoint
{
public:
C3point();
C3point(int x, int y, int z);
void disp();
private:
Cpoint p;
int m_z;
};
C3point::C3point():Cpoint()
{
m_z = 0;
cout<<"调用C3point默认构造函数"<<endl;
}
C3point::C3point(int x, int y, int z):Cpoint(x, y),p(x, y)
{
m_z = z;
cout<<"调用C3point构造函数"<<endl;
}
void C3point::disp()
{
int x;
int y;
p.getxy(x, y);
cout<<x<<","<<y<<","<<m_z<<endl;
}
int main()
{
C3point point1;
C3point point2(50, 80, 10);
Cpoint p(20,30);
p.disp();
point1.disp();
point2.disp();
return 0;
}