C++中的继承

#include <iostream>
class A{
    public:
        std::string head;
        void hello(std::string str){
            std::cout<<str<<head<<std::endl;
        }
};

int main()
{
   A a;
   std::string str="hello";
   a.head="888";
   a.hello(str);
   return 0;
}

写起来和java差不多,不同的地方在于这里是A a;java是A a=new A();

#include <iostream>
class A{
    public:
        std::string head;
        void hello(std::string str){
            std::cout<<str<<head<<std::endl;
        }
};
class B : public A{
    
};
int main()
{
   B a;
   std::string str="hello";
   a.head="888";
   a.hello(str);
   return 0;
}

这就是继承 C++直接用" : "表示了后面要public

C++构造器

#include <iostream>
class A{
    public:
        A(){
            printf("construction\n");
            
        };
        ~A(){
            printf("end construction\n");

        };
    
        std::string head;
        void hello(std::string str){
            std::cout<<str<<head<<std::endl;
        }
};
class B : public A{
    public:
        B(){
            printf("B construction\n");

        };
        ~B(){
            printf("end B construction\n");

        };
    
};
int main()
{
   B a;
   std::string str="hello";
   a.head="888";
   a.hello(str);
   return 0;
}

看一下输出,一看就能看懂很简单

construction
B construction
hello888
end B construction
end construction

 

posted @ 2023-04-16 13:29  Z_Chan  阅读(9)  评论(0编辑  收藏  举报