c++构造函数和结构体构造函数

今天写leetcode,让我对c++的一些知识有了更为深刻的认识。

        1.c++中的this

        c++中的this与js中类似,都是为了给类的实例创建变量和方法用的,使用this来获取实例上的方法和属性。

        2.构造函数中的this及初始化

        c++构造函数中,加不加this都可以将变量添加到类的实例上。例如:

不使用构造函数对变量进行初始化

#include <iostream>
using namespace std;
class A{
public:
    int a=5;
    int b=6;
    A(int tempa,int tempb){
    
    }
};

int main() {
    A* obj=new A(7,8);
    cout<<obj->a<<" "<<obj->b<<endl;
    return 0;
}

输出为:5,6

使用构造函数,不使用this对变量进行初始化:

#include <iostream>
using namespace std;
class A{
public:
    int a=5;
    int b=6;
    A(int tempa,int tempb){
        a=tempa;
        b=tempb;
    }
};

int main() {
    A* obj=new A(7,8);
    cout<<obj->a<<" "<<obj->b<<endl;
    return 0;
}

输出为:7,8

 使用构造函数,使用this对变量进行初始化:

#include <iostream>
using namespace std;
class A{
public:
    int a=5;
    int b=6;
    A(int tempa,int tempb){
        this->a=tempa;
        this->b=tempb;
    }
};

int main() {
    A* obj=new A(7,8);
    cout<<obj->a<<" "<<obj->b<<endl;
    return 0;
}

输出也是:7,8

由此可见:

        1.c++中,不用构造函数进行初始化,类中定义的变量也会加到实例上面

        2.c++构造函数中是否使用this初始化变量都是相同的

        3. c++类自己的方法和变量,是使用static来定义的 

但是在js的构造函数中,又是不一样了

function classa(x,y){
    let c=5;
    let d=6;
    this.x=x;
    this.y=y;
    console.log("this is classa");
    
}

let a=new classa(1,2);
console.log(a);

输出为: classa { x: 1, y: 2 }

js中,没有使用this来为实例添加属性c和d,因此,在对象a上,就找不到属性c和d。只有通过this添加的属性x和y,才能在对象a上找到。

        3.声明类数组

        在类Trie中,直接定义Trie * next[27]  即可

        4.c++结构体构造函数

#include "iostream"
#include "vector"

#include "queue"

#include "algorithm"
using namespace std;

struct node{
    int data;
    string str;
    char x;
    node() :x(), str(), data(){} ;
    node(int a, string b, char c) :data(a), str(b), x(c){};
}N[10];



int main()
{
    node *n=new node(1,"123",'c');
    cout<<n->data<<" "<<n->str<<" "<<n->x<<endl;
    return 0;



}

输出为:1 123 c

#include "iostream"
#include "vector"

#include "queue"

#include "algorithm"
using namespace std;

struct node{
    int data;
    string str;
    char x;
    node() :x(), str(), data(){} ;
    node(int a, string b, char c){
        this->data=a;
        this->str=b;
        this->x=c;
    }
}N[10];



int main()
{
    node *n=new node(1,"123",'c');
    cout<<n->data<<" "<<n->str<<" "<<n->x<<endl;
    return 0;



}

输出为: 1 123 c

因此,对于结构体构造函数来说

node(int a, string b, char c){
        this->data=a;
        this->str=b;
        this->x=c;
    }

node(int a, string b, char c) :data(a), str(b), x(c){};

效果是一样的 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值