h*****g 发帖数: 312 | 1 class Base{
public:
Base();
virtual ~Base();
};
class Derived: protected Base{
public:
virtual ~Derived();
};
int _tmain(int argc, _TCHAR* argv[])
{
Base *pd = new Derived;
getchar();
return 0;
}
Referring to the sample code above, which one of the following statements is
true?
A.
A constructor needs to be added to Derived class.
B.
The pointer returned by new cannot be type cast from Derived* to Base*.
C.
A pointer to a Base class cannot point to an instance of a Derived class.
D.
Derived class cannot have a virtual destructor.
E.
The code compiles with no errors.
答案是B。但查了半天没看懂为啥?看懂的能不能给详细的解释一下?难道是要call
baseclass的ctr to cast from Derived* to Base*?
class A
{
public:
void f{};
protected:
A(){};
A(const A&){}
}
Referring to the sample code above, why are the default and copy
constructors declared as protected?
A.
To ensure that instances of A can only be created by subclasses of A
B.
To ensure that instances of A cannot be created via new by a more derived
class
C.
To ensure that instances of A cannot be copied
D.
To ensure that A cannot be instantiated on the stack
E.
To ensure that A cannot be used as a base class
答案给的是A。 那如何由子类去创造 A 的object 呢?A * p= new subclass 可行吗?
能call A的ctr吗? | J*****n 发帖数: 4859 | 2 1. A constructor needs to be added to Derived class.
Because, in the derived, ur default one is from base one, which is protected
. So, when you call Base *pd = new Derived outside, ur can't access the
default constructor.
2. Need add a public constructor to do it. | j********t 发帖数: 97 | 3 1. 多态指针要求public inheritance。因为protected inheritance class的instance
不包含based class的private member,derived class instance无法转成based class
instance。
2. 子类通常在构造函数的初始化列表中初始化父类。 | n******m 发帖数: 169 | | s****p 发帖数: 19 | 5 1. B is not true. Surely you can cast a derived type pointer to a base type
one. this is just dynamic binding. The problem is that when doing
Base *pd = new Derived;
the pd pointer wants to bind to the base part of the Derived object, however
since the inheritance is protected, that part is inaccessible publicly, and
compiler reports an error.
If you change the inheritance label to public, it compiles with no error.
This also proves that casting derived pointer to base ptr is OK.
【在 h*****g 的大作中提到】 : class Base{ : public: : Base(); : virtual ~Base(); : }; : class Derived: protected Base{ : public: : virtual ~Derived(); : }; : int _tmain(int argc, _TCHAR* argv[])
| s****p 发帖数: 19 | 6
protected
This is not true. in the derived the default one is synthesized, and the
synthesized ctr automatically invoke the default ctr of the base class.
【在 J*****n 的大作中提到】 : 1. A constructor needs to be added to Derived class. : Because, in the derived, ur default one is from base one, which is protected : . So, when you call Base *pd = new Derived outside, ur can't access the : default constructor. : 2. Need add a public constructor to do it.
|
|