C++ 继承详解及实例代码

2020-01-06 15:52:23王振洲

这里服务器报错


derived12.cpp:13: error: `std::string base::testProtected()' is protected
derived12.cpp:62: error: within this context

这样就验证了一个是public,一个是protected,protected是不能直接调用的,但是被继承后是可以被public成员调用的。
下面的已经证明,详细步骤就略去如果对该部分验证感兴趣,可以看下面代码。


#include <iostream>
#include <string>
class base
{
  public:
    std::string testPublic()
    {
      return std::string("this is public base");
    }
  protected:
    std::string testProtected()
    {
      return std::string("this is protected base");
    }
  private:
    std::string testPrivate()
    {
      return std::string("this is private base");
    }
};

class derivedPublic:public base
{
  public:
    std::string testPubPublic()
    {
      return testPublic()+= "in derived";
    }
    
    std::string testProPublic()
    {  
      return testProtected()+= "in derived";
    }
    
//    std::string testPriPublic()          //私有成员并没有被继承下来
//    {  
//      return testPrivate()+= "in derived";
//    }
};

class deepDerived:public derivedPublic
{
  public:
    std::string test()
    {
      return testPublic() +="in 3";
    }
};

class derivedProtected:protected base
{
  public:
    std::string testPubProtected()
    {
      return testPublic()+= "in derived";
    }
    
    std::string testProProtected()
    {  
      return testProtected()+= "in derived";
    }
};

class deepDerived2:public derivedProtected
{
  public:
    std::string test()
    {
      return testPublic() +="in 3";
    }
};

class derivedPrivate:private base
{
  public:
    std::string testPubPirvate()
    {
      return testPublic()+= "in derived";
    }
    
    std::string testProPrivate()
    {  
      return testProtected()+= "in derived";
    }
    
};

//class deepDerived3:public derivedPrivate
//{
//  public:
//    std::string test()
//    {
//      return testPublic() +="in 3";
//    }
//};

int main(int argc,char* argv[])
{
  derivedPublic dpub;
  //derivedProtected dpro;
  //derivedPrivate dpri;
  std::cout<<dpub.testPublic()<<std::endl;    //
  //std::cout<<dpub.testProtected()<<std::endl;  //用户被继承也是无法使用
  //cout<<dpub.testPrivate()<<std::endl;     //基类都是私有函数
  std::cout<<dpub.testPubPublic()<<std::endl;
  std::cout<<dpub.testProPublic()<<std::endl;
  //std::cout<<dpub.testPriPrivate()<<std::endl; //没有被继承
  
  deepDerived dd;
  std::cout<<dd.test()<<std::endl;
    
  derivedProtected dpro;
  //std::cout<<dpro.testPublic()<<std::endl;    //变成protected类型
  std::cout<<dpro.testPubProtected()<<std::endl;
  std::cout<<dpro.testProProtected()<<std::endl;
    
  deepDerived2 dd2;
  std::cout<<dd2.test()<<std::endl;
    
  derivedPrivate dpri;
  std::cout<<dpri.testPubPirvate()<<std::endl;
  std::cout<<dpri.testProPrivate()<<std::endl;
  
//  deepDerived3 dd3;
//  std::cout<<dd3.test()<<std::endl;
}