您可以解构参数化的构造函数吗?

Can you deconstruct a parameterized constructor

本文关键字:构造函数 可以解 参数      更新时间:2023-10-16

我搜索了各种网站,看到了许多程序,但找不到单个程序。

#include <iostream>
using namespace std;
class Line {
   public:
      void setLength( double len );
      ~setLength(); <----- An error
      double getLength( void );
      Line();   // This is the constructor declaration
      ~Line();  // This is the destructor: declaration
   private:
      double length;
};
// Member functions definitions including constructor
Line::Line(void) {
   cout << "Object is being created" << endl;
}
Line::~Line(void) {
   cout << "Object is being deleted" << endl;
}
void Line::setLength( double len ) {
   length = len;
}
Line::~setLenght() //I tried void Line::~setLength too
{
 cout<<"The function is deleted:"
}
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;
}

我自己尝试过,但我没有工作,可能是我编写的代码不好,但我想知道是否有解构参数化的构造函数的选项,并将Void声明为参数(例如:line::line(void)(使其成为参数化的构造函数。

几点减轻您的困惑:

  1. setLength不是构造函数,它只是类Line的方法。
  2. 方法没有破坏者,只有类,并且总是称为~ClassName
  3. 如果它没有做任何有意义的事情(例如处理资源(,您实际上不需要提供灾难。
  4. void函数声明为单个参数是一种传统C来声明无参数的函数,并且在C 中实际上不需要。