C++ 程序的输出 |第 28 组(访问修饰符)
先决条件:c 中的访问修饰符,继承
1. 输出是什么?
C++
#include
using namespace std;
class access
{
int a = 10;
void disp()
{
cout<< "a: "<< a;
}
};
int main()
{
access a;
a.disp();
return 0;
}
C++
#include
using namespace std;
class access
{
private:
int a_pri = 10;
protected:
int b_pro = 20;
public:
int c_public = 30;
};
int main()
{
access a;
cout<< "private: " << a.a_pri;
cout<< "protected: "<< a.b_pro;
cout<< "public: " << a.c_public;
return 0;
}
C++
#include
using namespace std;
class access
{
protected:
int b_pro = 20;
public:
int c_public = 30;
};
class access_modifier: public access
{
public:
void disp()
{
cout<< "protected: "<< b_pro << endl;
cout<< "public: " << c_public << endl;
}
};
int main()
{
access_modifier a;
a.disp();
return 0;
}
C++
#include
using namespace std;
class rectangle
{
int x, y;
public:
void val (int, int);
int area ()
{
return (x * y);
}
};
void rectangle::val (int a, int b)
{
x = a;
y = b;
}
int main ()
{
rectangle rect;
rect.val (3, 4);
cout << "rect area: " << rect.area();
return 0;
}
C++
#include
using namespace std;
class access
{
public:
int a_public = 30;
};
class access_modifier: private access
{
};
class inheritance:public access_modifier
{
public:
void disp()
{
cout<< access::a_public;
}
};
int main()
{
inheritance a;
a.disp();
return 0;
}
输出:
Error
说明:如果未指定访问说明符,则默认情况下将它们视为私有。私有变量只能在类内访问,不能使用访问。如果不公开,运算符也是如此。
2. 输出是什么?
C++
#include
using namespace std;
class access
{
private:
int a_pri = 10;
protected:
int b_pro = 20;
public:
int c_public = 30;
};
int main()
{
access a;
cout<< "private: " << a.a_pri;
cout<< "protected: "<< a.b_pro;
cout<< "public: " << a.c_public;
return 0;
}
输出:
error
说明:不能在类外访问私有变量和受保护变量。
3. 输出是什么?
C++
#include
using namespace std;
class access
{
protected:
int b_pro = 20;
public:
int c_public = 30;
};
class access_modifier: public access
{
public:
void disp()
{
cout<< "protected: "<< b_pro << endl;
cout<< "public: " << c_public << endl;
}
};
int main()
{
access_modifier a;
a.disp();
return 0;
}
输出:
protected: 20
public: 30
说明:受保护的变量只能在从它派生的一个中访问。这里我们不能打印 a_pri,因为它是一个私有成员,并且无论继承类型如何,它们都不能在派生类中访问。
4. 输出是什么?
C++
#include
using namespace std;
class rectangle
{
int x, y;
public:
void val (int, int);
int area ()
{
return (x * y);
}
};
void rectangle::val (int a, int b)
{
x = a;
y = b;
}
int main ()
{
rectangle rect;
rect.val (3, 4);
cout << "rect area: " << rect.area();
return 0;
}
输出:
rect arera: 12
说明:由于 area() 和 val() 都被声明为 public 它们可以在类之外访问。
5. 输出是什么?
C++
#include
using namespace std;
class access
{
public:
int a_public = 30;
};
class access_modifier: private access
{
};
class inheritance:public access_modifier
{
public:
void disp()
{
cout<< access::a_public;
}
};
int main()
{
inheritance a;
a.disp();
return 0;
}
输出:错误
描述:当一个类被派生为私有继承时,它的变量就变成私有的,只能在该类中访问,并且在进一步继承时无法访问。