class Point {double x,y;
public:Point(double x =0,double y =0){ this -> x = x; this -> y =y;}doublegetx(){return x;}doublegety(){return y;}voidsetx(double x){this -> x = x;}voidsety(double y){this -> y = y;}};
class Line {
public:
Point p1,p2;Line(Point a,Point b):p1(a),p2(b){}};intmain(){
Point a,b;
Line L(a,b);
L.p1.setx(3); L.p1.sety(4);//直接访问成员类return0;}
class Point {double x,y;
public:Point(double x =0,double y =0){ this -> x = x; this -> y =y;}doublegetx(){return x;}doublegety(){return y;}voidsetx(double x){this -> x = x;}voidsety(double y){this -> y = y;}};
class Line {
Point p1,p2;
public:Line(Point a,Point b):p1(a),p2(b){}doublegetDistance(){double detax,detay;
detax = p1.getx()- p2.getx();
detay = p1.gety()- p2.gety();returnsqrt(detax * detax + detay * detay);}voidsetp1(double x,double y){ p1.setx(x); p1.sety(y);}};intmain(){
Point a,b;
Line L(a,b);
L.setp1(3,4);//通过Line的public函数访问return0;}
对向成员初始化
上述例子中,Line的创建必须要两个Point才能成功创建
成员对象初始化也可以设置默认值,成员初始化的顺序和成员声明的次序相同,下面重写Line类构造函数:
class Line {
Point p1,p2;
public:Line(Point a,Point b):p1(a),p2(b){}Line(double ax =0,double ay =0,double bx =0,double by =0):p2(bx,by),p1(ax,ay){}//虽然p2在前,但是根据声明顺序,先构造p1};intmain(){
Line L1(3,4), L2,L3(3,4,5,6);return0;}
class Shape {
public:voiddraw()const{...}doublearea()const{...}voidmove(int){...}};
class Line : public Shape {
private:
Shape::area;//Line没有area,将接口隐藏};
#include<iostream>
using namespace std;
class Base {int bm;
public:Base(int v =0):bm(v){cout<<"Base构造函数"<<endl;}~Base(){cout<<"Base析构函数"<<endl;}};
class Member {int mm;
public:Member(int v =0):mm(v){cout<<"Member构造函数"<<endl;}~Member(){cout<<"Member析构函数"<<endl;}};
class Derived : public Base {
Member dm;
public:Derived(int num =0):dm(num){cout<<"Derived构造函数"<<endl;}~Derived(){cout<<"Derived析构函数"<<endl;}};intmain(){
Derived d;return0;}
class B1 {
public:voidf();voidg();};
class B2 {
public:voidf();voidh();};
class D : public B1, public B2 {...}int main (){
D obj;
obj.f();//错误,有二义性
obj.B1::f();//正确,调用B1::f()
obj.B2::f();//正确,调用B2::f()};