qianbiao 发表于 2022-8-6 08:43:16

c++带参数的类构造函数的问题

#include <iostream>

using namespace std;

class Line
{
   public:
      void setLength( double len );
      double getLength( void );
      Line(double len);// 这是构造函数

   private:
      double length;
};

// 成员函数定义,包括构造函数
Line::Line( double len)
{
    cout << "Object is being created, length = " << len << endl;
    length = len;
}

void Line::setLength( double len )
{
    length = len;
}

double Line::getLength( void )
{
    return length;
}
// 程序的主函数
int main( )
{
   Line line(10.0);

   // 获取默认设置的长度
   cout << "Length of line : " << line.getLength() <<endl;
   // 再次设置长度
   line.setLength(6.0);
   cout << "Length of line : " << line.getLength() <<endl;

   return 0;
}

标黄的地方不太懂(第35行),是声明了一个对象吗?

dolly_yos2 发表于 2022-8-6 09:12:07

如果想明确一些的话,这里声明、定义并(直接)初始化了一个对象,初始化过程中调用了构造函数。
页: [1]
查看完整版本: c++带参数的类构造函数的问题