How to write a simple class in C++?

后端 未结 4 573
夕颜
夕颜 2020-12-13 13:42

I have been reading a lot of tutorials on C++ class but they miss something that other tutorials include.

Can someone please show me how to write and use a very simp

4条回答
  •  时光说笑
    2020-12-13 13:59

    #include 
    #include 
    
    class Simple {
    public:
      Simple(const std::string& name);
      void greet();
      ~Simple();
    private:
      std::string name;
    };
    
    Simple::Simple(const std::string& name): name(name) {
      std::cout << "hello " << name << "!" << std::endl;
    }
    
    void Simple::greet() {
      std::cout << "hi there " << name << "!" << std::endl;
    }
    
    Simple::~Simple() {
      std::cout << "goodbye " << name << "!" << std::endl;
    }
    
    int main()
    {
      Simple ton("Joe");
      ton.greet();
      return 0;
    }
    

    Silly, but, there you are. Note that "visibility" is a misnomer: public and private control accessibility, but even "private" stuff is still "visible" from the outside, just not accessible (it's an error to try and access it).

提交回复
热议问题