题:找出下面程序的错误,并解释它为什么是错的。【中国台湾某著名杀毒软件公司2005年面试题】
// P138_example2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
class Base
{
public:
int val;
Base()
{
val = 1;
}
};
class Derive : Base
{
public:
int val;
Derive(int i)
{
val = Base::val + i;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Derive d(10);
std::cout<<d.Base::val<<std::endl<<d.val<<std::endl;
return 0;
}
解析:这是个类继承问题。如果不指定public,C++默认的是私有继承。私有继承是无法继承并使用父类函数中的公有变量的。
答案:把class Derive:Base改成class Derive:public Base。