C++ 默认构造函数


类构造函数是类的特殊成员函数,它在创建该类的对象的时候执行。

构造函数的名称与类的名称完全相同,但它没有任何返回类型,甚至连 void 都没有。构造函数对于为某些成员变量设置初始值非常有用。

下面的例子说明了构造函数的概念 −

示例

 在线示例

#include <iostream>
using namespace std;
class Line {
   public:
      void setLength( double len );
      double getLength( void );
      Line(); // This is the constructor
      private:
      double length;
};
// Member functions definitions including constructor
Line::Line(void) {
   cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
   length = len;
}
double Line::getLength( void ) {
   return length;
}
// Main function for the program
int main() {
   Line line;
   // set line length
   line.setLength(6.0);
   cout << "Length of line : " << line.getLength() <<endl;
   return 0;
}

输出

Object is being created
Length of line : 6

更新日期:2019 年 7 月 30 日

234 人查看

开启您的 职业

完成课程即可获得认证

开始
广告
© . All rights reserved.