C++类与对象基础

利用寒假时间,对C++有一个全面基础性的了解


类外定义成员函数时可以访问私有成员,而在main函数中不能输出私有成员


#include<iostream>
using namespace std;
class Time
{
public:
	void set_time();
        Time (int newH,int newM,int newS);//构造函数
 private:
	int hour;		//成员函数
	int minute;
	int second;
};
Time::Time(int newH,int newM,int newS)
{//构造函数的实现
hour=newH;mintue=newM;second=newS;
}
int main()
{
	Time t1;//定义对象t1
	t1.set_time();//调用对象t1的成员函数set_time()
	return 0;
}

void Time::set_time()
{//类外定义函数,注意 类名::函数名
	cin >> hour;
	cin >> minute;
	cin >>second;
}




多个文件写程序

//arraymax.cpp 成员函数的定义
#include<iostream>
#include"araymax.h"
using namespace std;

void Max::set_value()
{
	int i;
	for (i = 0; i < 4; i++)
		cin >> a[i];
}
void Max::max_value()
{
	 max = a[0];
	for (int i = 1; i < 4; i++)
	{
		if (a[i]>max) max = a[i];
	}
}
void Max::show_value()
{
	cout << max << endl;
}
//arraymax.h 类定义
class Max
{
public:
	void set_value();
	void max_value();
	void show_value();
private:
	int a[4];
	int max;
};

//源.cpp main函数
#include<iostream>
#include"araymax.h"

using namespace std;


int main()
{
	Max arrmax;
	arrmax.set_value();
	arrmax.max_value();
	arrmax.show_value();
	return 0;
}

类外定义构造函数

#include<iostream>
using namespace std;

class Box
{
public:
	Box(int, int, int);//声明带参数的构造函数
	int volume();
private:
	int length;
	int width;
	int high;
};

int main()
{
	Box box1(2, 3, 6);
	cout << "The value  of box1 is" << box1.volume() << endl;
	Box box2(3, 5, 7);
	cout << "The value of box2 is" << box2.volume() << endl;

	return 0;
}
Box::Box(int l, int w, int h)
{//在类外定义构造函数
	length = l;
	width = w;
	high = h;
}
int Box::volume()
{
	return (length*width*high);
}


利用参数初始化表初始化,定义对象数组

#include<iostream>
using namespace std;

class Box
{
public:
	//声明默认参数构造函数,用参数初始化表对数据成员初始化
	Box(int l = 10, int w = 20, int h = 30) :length(l), width(w), high(h){}
	int volume();
	private:
		int length;
		int width;
		int high;
};
int Box::volume()
{
	return length*width*high;
}
int main()
{
	Box box[3]={//定义对象数组
		Box(2, 2, 2), //调用构造函数Box,提供第一个元素的实参
		Box(3, 3, 3), 
		Box(4, 4, 4)
	};
	cout << box[0].volume() << endl;
	cout << box[1].volume() << endl;
	cout << box[2].volume() << endl;
	return 0;
}

指向对象的指针

#include<iostream>
using namespace std;

class Time
{
public:
	Time(int D=1,int h=1, int m=1, int s=1) :Day(D),hour(h), minute(m), second(s){}
	void show_time();
	int Day;
private:
	int hour;
	int minute;
	int second;
};

int main()
{
	Time t1(1,11, 59, 22);//创建对象t1
	t1.show_time();
	int *p1 = &t1.Day;//定义指向整型数据(public)的指针变量
	cout << *p1 << endl;
	
	Time *p2 = &t1;//定义指向对象t1的指针变量p2
	p2->show_time();//调用p2所指对象(t1)的函数

	void (Time::*p3)();//定义指向Time类公用成员函数的指针变量
	p3 = &Time::show_time;//前两句可以合并成void (Time::*p3)()=&Time::show_time;
	(t1.*p3)();//相当于t1.show_time();

	return 0;
}
void Time::show_time()
{
	cout<<Day<<":" << hour <<":"<< minute<<":" << second<<endl;
}

友元函数

#include<iostream>
using namespace std;

class Date;//对Date类的提前引用声明
class Time
{
public:
	Time(int h, int m, int s) :hour(h), minute(m), second(s){}
	void display(Date &);//形参是Date类对象的引用
private:
	int hour;
	int minute;
	int second;
};
class Date
{
public:
	Date(int y, int m, int d) :year(y), month(m), day(d){}
	friend void Time::display(Date &);//声明Time中的display函数为本类的友元成员函数
private:
	int year;
	int month;
	int day;
};

void Time::display(Date &d)
{
	cout << d.year << "/" << d.month << "/" << d.day<<endl;
	cout << hour << ":" << minute << ":" << second << endl;
}
int main()
{
	Time t1(20, 16, 22);
	Date d1(2016, 1, 14);
	t1.display(d1);
	return 0;
}

类模版的使用

#include<iostream>
using namespace std;

template<class numtype>	//定义类模版,虚拟类型名为numtype,注意无分号
class Compare
{
public:
	Compare(numtype a, numtype b) :x(a), y(b){}
	numtype max();
	numtype min();
private:
	numtype x;
	numtype y;
};
template<class numtype>
numtype Compare<numtype>::max()
{//类外定义成员函数,注意格式
	return x > y ? x : y;
}
template<class numtype>
numtype Compare<numtype>::min()
{
	return x > y ? y : x;
}
int main()
{
	Compare <int> cmp1(3, 7);
	cout << "max is " << cmp1.max() << endl;
	Compare <float> cmp2(2.05, 5.5);
	cout << "min is " << cmp2.min() << endl;
	Compare <char> cmp3('a', 'c');
	cout << "min is " << cmp3.min() << endl;

}

运算符重载

讲add函数全改为operator+即可

运算符被重载后,原有的功能仍然保留,没有丧失,要执行哪种功能由系统根据上下文决定

注意:c++不允许用户自定义新的运算符,只能对已有的运算符进行重载,等等详情见书。

#include<iostream>
using namespace std;

class Complex
{
public:
	Complex(double a = 0, double b = 0) :rear(a), imag(b){}
	Complex operator+(Complex &);//声明重载运算符+的函数,函数名为operator+,函数类型为Coplex类
	//一般情况下,运算的左元是定义的类中的对象,若想传递两个参数,在前加friend,变成友元函数。
	void display();
private:
	double rear;//实部
	double imag;//虚部
};
Complex Complex::operator+(Complex &c)
{
	Complex c1;
	c1.rear = c.rear + rear;
	c1.imag = c.imag + imag;
	return c1;
}//可简练为 return Complex(rear+c.rear,imag+c.imag);
 void Complex::display()
{
	cout << "("<<rear << "." << imag <<"i)"<< endl;
}
int main()
{
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;//编译系统解释为c3=c1.operator+(c2);
	//可以c4=c1+c2+c3;实现多个对象相加
       cout << "c1=";	c1.display();
	cout << "c2=";	c2.display();
	cout << "c3=";	c3.display();
	return 0;
}

重载函数作为友元函数

#include<iostream>
using namespace std;

class Complex
{
public:
	Complex(double r = 0, double i = 0) :rear(r), imag(i){}
	void display();
	friend Complex operator+(Complex &, Complex &);//重载函数作为友元函数
private:
	double rear;
	double imag;
};

void Complex::display()
{
	cout << "(" << rear << "." << imag <<")"<< endl;
}
Complex operator+(Complex &c1,Complex &c2)
{
	return Complex(c1.rear + c2.rear, c1.imag + c2.imag);
}
int main()
{
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;
	c3.display();
}

重载双目运算符

#include<iostream>
#include<string>
using namespace std;

class String
{
public:
	String(char *s) {p = s; }//注意
	void display();
	friend bool operator>(String &, String &);
private:
	char *p;
};
void String::display()
{
	cout << p << endl;
}
bool operator>(String &s1, String &s2)
{
	if (strcmp(s1.p, s2.p) > 0)
		return true;
	else return false;
}
int main()
{
	String string1("hello"),string2("suyi");
	string1.display();
	string2.display();
	cout << (string1 > string2) << endl;
}


重载单目运算符

/*
重载单目运算符,1.17  23:23
*/
#include<iostream>
using namespace std;

class Time
{
public:
    Time(int m=0,int s=0):minute(m),second(s){}
    Time operator++();//声明前置自增运算符“++重载函数
    Time operator++(int);//声明后置自增运算符“++”重载函数,int参数只是为了区分前置和后置
    void display();
private:
    int minute;
    int second;
};

Time Time::operator++()
{
    if(++second>=60)
    {
        second-=60;
        ++minute;
    }
    return *this;   //注意
}
Time Time::operator++(int)
{
    Time temp(*this);   //建立临时对象temp;
    if(second++>=60)
    {
        second-=60;
        ++minute;
    }
    return temp;    //返回的是自加前的对象
}
void Time::display()
{
    cout<<minute<<":"<<second<<endl;
}
int main()
{
    Time time1(34,59),time2;
    cout<<"time1:";time1.display();
    ++time1;
    cout<<"++time1后的time1:";time1.display();
    time2=time1++;
    cout<<"time1++后的time1";time1.display();
    cout<<"time2";time2.display();

    return 0;
}


简单派生类的构造函数和析构函数

/*
注意派生类构造函数的形式
冒号前是派生类构造函数的主干,参数包括基类构造函数所需的参数和派生类新增的数据成员初始化所需的参数,包括参数类型和参数名
冒号后是要调用的基类构造函数及其参数,不包括参数类型
*/
#include<iostream>
#include<string>

using namespace std;

class Student
{
public:
    Student(int n,string nam,char s)
    {//定义基类构造函数
        num=n;
        name=nam;
        sex=s;
    }
    ~Student(){}    //基类析构函数
protected:
    int num;
    string name;
    char sex;
};
class Student1:public Student
{//声明公用派生类Student1
public:
    Student1(int n,string nam,char s,int a,string ad):Student(n,nam,s)
    {//定义派生类构造函数
        age=a;
        addr=ad;
    }
//或者Student1(int n,string nam,char s ,int a,string ad):Student(n,nam,s),age(a),addr(ad){}    
//类外定义构造函数Student1::Student1(int n,string nam,char s,int a,string ad):Student(n,nam,s){age=a;addr=ad; }
~Student1(){}//派生类析构函数
    void show()
    {
        cout<<"num:"<<num<<endl;//公用继承,可以访问基类的protected成员
        cout<<"name :"<<name<<endl;
        cout<<"sex:"<<sex<<endl;
        cout<<"age"<<age<<endl;
        cout<<"address"<<addr<<endl;
    }
private:
    int age;
    string addr;
};

int main()
{
    Student1 stud1(10010,"Wang-Lin",'f',19,"Beijing");
    Student1 stud2(10011,"Zhang-fang",'m',21,"Shanghai");
    stud1.show();
    stud2.show();
return 0;
}


/*
Point类的构造函数是内联成员函数
如果没有定义复制构造函数,系统会为你生成一个默认的复制构造函数
Point类复制构造函数被调用4次,xp1,xp2先被传了实参后,调用两次Point复制构造函数,然后xp1,xp2去初始化p1,p2又
调用两次Point类复制构造函数
*/
#include<iostream>
#include<cmath>
using namespace std;

class Point		//Point类的定义
{
public:
	Point(int xx = 0, int yy = 0)//自定义构造函数
	{
		x = xx;
		y = yy;
	}
	Point(Point &p);//复制构造函数,用同一类的对象来初始化另一对象
	int getX()
	{return x;}
	int getY()
	{return y;}
private:
	int x, y;
};

Point::Point(Point &p) //复制构造函数的实现(调用类的成员函数::)
{
	x = p.x;
	y = p.y;
	cout << "调用Point类复制构造函数" << endl;
}

//类的组合,1个类里内嵌了其他类的对象作为成员
class Line
{
public:
	Line(Point xp1, Point xp2);  //构造函数
	Line(Line &l);	//复制构造函数
	double getlen()
	{return len;}
private:
	Point p1, p2; //Point类的对象p1,p2
	double len;
};

//组合类的构造函数
Line::Line(Point xp1, Point xp2) :p1(xp1), p2(xp2)
{
	cout << "调用Line类构造函数"<< endl;
	double x = static_cast<double>(p1.getX() - p2.getX());
	double y = static_cast<double>(p1.getY() - p2.getY());
	len = sqrt(x*x + y*y);
}
int main()
{
	Point myp1(1,1), myp2(4, 5);
	Line line(myp1, myp2);
	cout << "line的长度为" << endl;
	cout << line.getlen() << endl;
	return 0;
}


<pre name="code" class="cpp">#include<iostream>

using namespace std;

class Point
{
public:
    Point(float x=0,float y=0); //有默认参数的构造函数
    void setPoint(float,float);
    float getX() const { return x;}
    float getY() const { return y;}
    friend ostream & operator <<(ostream &, const Point &);//友元重载运算符<<
protected:
    float x,y;
};
//Point的构造函数
Point::Point(float a, float b)
{
    x=a;
    y=b;
}

void Point::setPoint(float a, float b)
{
    x=a;y=b;
}
//重载运算符<<,使之能输出点的坐标
ostream & operator <<(ostream &output,const Point &p)
{
    output<<"["<<p.x<<"'"<<p.y<<"]"<<endl;
    return output;
}


class Circle:public Point
{
public:
    Circle(float x=0,float y=0,float r=0);
    void setRadius(float);
    float getRadius()const;
    float area() const; //计算圆面积
    friend ostream &operator <<(ostream &,const Circle &);
protected:
    float radius;
};

Circle ::Circle(float x, float y, float r):Point(x,y),radius(r){}

void Circle::setRadius(float r)
{
    radius=r;
}

float Circle::getRadius() const { return radius; }

float Circle::area() const { return 3.14159*radius*radius;}

ostream & operator<<(ostream &output,const Circle &c)
{
    output<<"Centar=["<<c.x<<","<<c.y<<"],r"<<c.radius<<",area="<<c.area()<<endl;
    return output;
}

class Cylinder: public Circle
{
public:
    Cylinder(float x=0,float y=0,float r=0,float h=0);
    void setHeight(float);
    float getHeight()const;
    float area()const;
    float volume()const;
    friend ostream &operator<<(ostream &,const Cylinder &);
protected:
    float height;
};

Cylinder::Cylinder(float x, float y, float r, float h) :Circle(x,y,r),height(h){}
void Cylinder::setHeight(float h) {height=h; }
float Cylinder::getHeight() const {return height; }
float Cylinder::area() const
{return 2*Circle::area()+2*3.14159*radius*height; }
float Cylinder::volume() const
{return Circle::area()*height; }
ostream & operator <<(ostream & output,const Cylinder &cy)
{
output<<"Center=["<<cy.x<<","<<cy.y<<"],r="<<cy.radius<<",h="<<cy.height<<",area="
    <<cy.area()<<",volume="<<cy.volume()<<endl;
    return output;
}


int main()
{
    Cylinder cy1(3.5,6.4,5.2,10);
    cout<<"original cylinder:\nx="<<cy1.getX()<<",y="<<cy1.getY()<<
    ",r=" <<cy1.getRadius()<<",area="<<cy1.area()<<",volume="<<cy1.volume()<<endl;
    cy1.setHeight(15);
    cy1.setRadius(7.5);
    cy1.setPoint(5,5);        //设置圆心坐标值
    cout<<"new cylinder\n"<<cy1;
    Point &pRef=cy1;  //pRef是Point类的引用,被c初始化;
    cout<<"\n pRef as a point:"<<pRef;
    Circle &cRef=cy1;  //pRef是Point类的引用,被c初始化;
    cout<<"\n cRef as a circle:"<<cRef;
    return 0;
}





                
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值