struct Point
{
int x; // 合法
int y; // 合法
void print()
{
printf("Point print/n"); //編譯錯誤
};
}9 ;
#include <iostream>
using namespace std;
class CPoint
{
int x; //默認(rèn)為private
int y; //默認(rèn)為private
void print() //默認(rèn)為private
{
cout << "CPoint: (" << x << ", " << y << ")" << endl;
}
public:
CPoint(int x, int y) //構(gòu)造函數(shù),指定為public
{
this->x = x;
this->y = y;
}
void print1() //public
{
cout << "CPoint: (" << x << ", " << y << ")" << endl;
}
};
struct SPoint
{
int x; //默認(rèn)為public
int y; //默認(rèn)為public
void print() //默認(rèn)為public
{
cout << "SPoint: (" << x << ", " << y << ")" << endl;
}
SPoint(int x, int y) //構(gòu)造函數(shù),默認(rèn)為public
{
this->x = x;
this->y = y;
}
private:
void print1() //private類型的成員函數(shù)
{
cout << "SPoint: (" << x << ", " << y << ")" << endl;
}
};
int main(void)
{
CPoint cpt(1, 2); //調(diào)用CPoint帶參數(shù)的構(gòu)造函數(shù)
SPoint spt(3, 4); //調(diào)用SPoint帶參數(shù)的構(gòu)造函數(shù)
cout << cpt.x << " " << cpt.y << endl; //編譯錯誤
cpt.print(); //編譯錯誤
cpt.print1(); //合法
spt.print(); //合法
spt.print1(); //編譯錯誤
cout << spt.x << " " << spt.y << endl; //合法
return 0;
}
main函數(shù)內(nèi)的編譯錯誤全部是因為訪問private成員而產(chǎn)生的。因此我們可以看到class中默認(rèn)的成員訪問權(quán)限是private的,而struct中則是public的。在類的繼承方式上,struct和class又有什么區(qū)別?請看下面的程序:
#include <iostream>
using namespace std;
class CBase
{
public:
void print() //public成員函數(shù)
{
cout << "CBase: print()..." << endl;
}
};
class CDerived1 : CBase //默認(rèn)private繼承
{
};
class CDerived2 : public Cbase //指定public繼承
{
};
struct SDerived1 : Cbase //默認(rèn)public繼承
{
};
struct SDerived2 : private Cbase //指定public繼承
{
};
int main()
{
CDerived1 cd1;
CDerived2 cd2;
SDerived1 sd1;
SDerived2 sd2;
cd1.print(); //編譯錯誤
cd2.print();
sd1.print();
sd2.print(); //編譯錯誤
return 0;
}