类与对象简写

一:类的使用和类中基本的语法:

(1):在C++中,新的数据类型可以用class来构造,称为类类型。class声明的语法与C语言中的struct声明相似,但class中还可以包含函数声明。

  1:类名(people)  对象名1(he),*对象名2(she); //she是一个类类型的指针。

  2:类成员访问机制:私有成员,公有成员,保护成员。

  3:构造函数,析构函数。

  4:标准库类型;string。string s;表明创建一个string对象。string s = string y;把对象y拷贝给对象s。在这个过程会执行拷贝构造函数。(下一节)

    构造函数:当一个对象被创建时,在C++中通过构造函数对对象进行初始化,即每当对象被声明或在堆栈中被分配或由new运算符创建时,

                     构造函数即被调用。

    析构函数:析构函数是类的成员函数。它的名字与类名相同,只是在前面加了一个符号“~”。析构函数不接受任何参数,也不返回任何说明

         的类型和值。

#include <iostream>
#include <string> 
using namespace std;//using命名空间的空间的声明, 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class people
{
    public:
        people()
        {
            cout<<"输出无参数的构造函数"<<endl;
            this->other_people("no replay");
            }    
        people(string x,int y)
        {
            cout<<"输出有参数的构造函数"<<x<<endl;

            this->other_people(x);
            }
         ~people()   //为什么会一直执行析构函数。 
        {
            cout<<"执行析构函数"<<endl;
            //delete this;// 为什么delete this的时候会进入死循环。:因为调用delete删除对象的时候会自动调用该类的析构函数.
            //也就是说,不需要你手动delete this,调用析构函数就是删除对象释放内存,不需要在手动添加delete函数。 
        }

        void read_other()
        {
            cout<<"other_people"<<this->other_peoples;//this代替的是当前对象. 
         } 
    private:
        int other_people(string s); //声明, 私有成员类外不能访问.除(友元类,友元函数) 
        string other_peoples;

};
int people::other_people(string s="没有告诉我对象叫什么名字")
{
    this->other_peoples = s;
    cout<<"other_people"<<other_peoples<<endl; 
    return 0;
}
int main(int argc, char** argv)
{
    string s;
    cin>>s;
    //int g1,g2;
    //cin>>g1>>g2; //把第一个输入到g1第二个输入到g2。 
    //cout<<g1<<"and"<<g2<<endl;
    people big_people(s,4);
    return 0;
}

 

原文链接: https://www.cnblogs.com/1314bjwg/p/12396231.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    类与对象简写

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/333056

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午8:57
下一篇 2023年3月1日 下午8:57

相关推荐