struct Point
{
int x; // 合法
int y; // 合法
void print()
{
printf("Point print/n"); //编译错误
};
}9 ;
#include <iostream>
using namespace std;
class CPoint
{
int x; //默认为private
int y; //默认为private
void print() //默认为private
{
cout << "CPoint: (" << x << ", " << y << ")" << endl;
}
public:
CPoint(int x, int y) //构造函数,指定为public
{
this->x = x;
this->y = y;
}
void print1() //public
{
cout << "CPoint: (" << x << ", " << y << ")" << endl;
}
};
struct SPoint
{
int x; //默认为public
int y; //默认为public
void print() //默认为public
{
cout << "SPoint: (" << x << ", " << y << ")" << endl;
}
SPoint(int x, int y) //构造函数,默认为public
{
this->x = x;
this->y = y;
}
private:
void print1() //private类型的成员函数
{
cout << "SPoint: (" << x << ", " << y << ")" << endl;
}
};
int main(void)
{
CPoint cpt(1, 2); //调用CPoint带参数的构造函数
SPoint spt(3, 4); //调用SPoint带参数的构造函数
cout << cpt.x << " " << cpt.y << endl; //编译错误
cpt.print(); //编译错误
cpt.print1(); //合法
spt.print(); //合法
spt.print1(); //编译错误
cout << spt.x << " " << spt.y << endl; //合法
return 0;
}
main函数内的编译错误全部是因为访问private成员而产生的。因此我们可以看到class中默认的成员访问权限是private的,而struct中则是public的。在类的继承方式上,struct和class又有什么区别?请看下面的程序:
#include <iostream>
using namespace std;
class CBase
{
public:
void print() //public成员函数
{
cout << "CBase: print()..." << endl;
}
};
class CDerived1 : CBase //默认private继承
{
};
class CDerived2 : public Cbase //指定public继承
{
};
struct SDerived1 : Cbase //默认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;
}