gpt4 book ai didi

c++ - 你能解构一个参数化的构造函数吗

转载 作者:行者123 更新时间:2023-11-30 03:15:51 25 4
gpt4 key购买 nike

我搜索了各种网站,看到了很多程序,但找不到一个程序在做。这里是教程点的一个例子

#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++ 中实际上并不需要。此外,它并不是真正特定于析构函数。

关于c++ - 你能解构一个参数化的构造函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56747312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com