繁体   English   中英

将值从构造函数传递到类中的私有整数

[英]Passing value from constructor to private integer within class

我有使用Java的经验,但是最近开始使用C ++进行工作,但在理解如何将内容存储在C ++中的过程中遇到了一些麻烦。 在Java中,以下内容有效:

class Class {
    int myInt;

    public Class(int myInt) {
        this.myInt = myInt;
    }
}

所以我在类中有一个整数,在创建对象时给它一个值。 我想在C ++中复制它:

class Class {
        int myInt;
    public:
        Class (int myInt) {
            // What goes here?
        }
};

但是,这不起作用。 如果我将传递给构造函数的变量命名为myInt以外的其他myInt ,则只需声明myInt = differentName 但是假设像在Java中一样,我希望传递给构造函数的变量和变量的名称都相同吗? 我该如何实现?

两种选择:

  • 使用初始化列表

     class Class { int myInt; public: Class (int myInt) : myInt(myInt) { } }; 
  • 您有意寻找的是:

     class Class { int myInt; public: Class (int myInt) { Class::myInt = myInt; } }; 

但是第一个是首选。

您只需要使用构造函数初始化列表:

class Class {
        int myInt;
    public:
        Class (int myInt) : myInt(myInt) 
        {
          // by the time you get here, myInt is already initialized.
          // You can assign a value to it or modify it otherwise, 
          // but you cannot initialize something more than once.
        }
};

这是在构造函数中显式初始化数据成员的唯一方法。 进入构造函数主体后,所有数据成员都已初始化。

除初始化程序语法外,C ++中也提供this语法。 您可以将其用作this->myInt因为this是一个指针。

“ this”是C ++中的指针。 所以会

this->myInt = myInt;

以下是在c ++中实现相同的方法this-> myInt = myInt;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM