构造函数和“this"指针 [英] Constructor and "this" pointer

查看:48
本文介绍了构造函数和“this"指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习 C++,并在教程中找到了下面的课程.我的问题与构造函数有关.课程是:

i started studying c++ and i found the class below in a tutorial. My question has to do with the constructor. the class is:

class point{
private:
    double *x;
    double *y;
public:
    point(double x=1,double y=1);
    //....
};

构造函数是:

point::point(double x,double y)
{
    this->x = new double;
    *(this->x)=x;
    this->y = new double;
    *(this->y)=y;

    }

我想问一下为什么下面的代码是错误的?为什么我必须使用这个"?

i wanted to ask WHY is the following code wrong? why do i have to use "this"?

 point::point(double x,double y)
    {
        x = new double;
        *x=x;
        y = new double;
        *y=y;

    }

推荐答案

您的编译器如何知道 x 参数和 x 类的字段之间的区别?

How would your compiler know the difference between x the parameter and x the field of the class ?

this->x 表示属于我所在类的x变量,即:point

如果你在_x类中调用了字段x,你可以在构造函数中写*_x = x

If you called the field x in the class _x, you could write *_x = x in the constructor

PS:是的,同意评论,这不是一个好的教程 x)

PS: Yes, agreed with the comments, this is NOT a good tutorial x)

更多信息:http://en.cppreference.com/w/cpp/语言/这个

这篇关于构造函数和“this"指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆