ISO C++禁止声明无类型的'auto_ptr'

ISO C++ forbids declaration of 'auto_ptr' with no type

本文关键字:ptr auto 禁止 C++ 声明 类型 ISO      更新时间:2023-10-16

我正试图编写一个小型应用程序,但在使用auto_ptr时遇到了编译时错误。

我最初厌倦了用我创建的类创建智能指针,但如果我尝试创建int类型的智能指针,也会发生同样的错误,所以我一定做错了其他事情。我是按照这里的例子做的。。

我有一种感觉,这个答案会让我打自己一巴掌。

我在这个文件的底部声明智能指针。

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <memory.h>
#include <QMainWindow>
#include "dose_calac.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    /*
     Some QT stuff here, removed for clarity / size...
    */
private:
    Ui::MainWindow *ui;
    /*
      Object for storage of data and calculation of DOSE index score.
    */
    std::auto_ptr<int> pdoseIn(new int); // A simple set case, but sill produces an error!?!
    std::auto_ptr<DOSE_Calac> pdoseIn(new DOSE_Calac); // Original code, error found here at first.
};
#endif // MAINWINDOW_H

这是我的课,dose_calac.h。

#ifndef DOSE_CALAC_H
#define DOSE_CALAC_H
class DOSE_Calac
{
public:
// constructor
    DOSE_Calac();
// set and get functions live here, removed for clarity / size.
// function for caulating DOSE indexpoints
    int CalcDOSEPoints();
private:
    unsigned int dyspnoeaScale;
    unsigned int fev1;
    bool smoker;
    unsigned int anualExacerbations;
    unsigned int doseIndexPoints;
};
#endif // DOSE_CALAC_H

感谢收到的任何帮助或建议。

您的错误是由包含不正确的标头引起的。代替

#include <memory.h>

你应该写

#include <memory>

此外,在类定义中还有更严重的错误,因为不能以这种方式初始化类成员:

std::auto_ptr<int> pdoseIn(new int);

您必须单独声明它并在构造函数中初始化:

std::auto_ptr<int> pdoseIn;
MainWindow()
    : pdoseIn(new int)
{}

您不能像那样初始化类成员变量,您需要在类声明中通过执行std::auto_ptr<int> a;来定义它,并在ctor中使用a(new int)来初始化它。

不能像这样初始化类声明中的数据成员:

class MainWindow
{
    std::auto_ptr<int> pdoseIn(new int);
};

您需要像这样声明成员,并在构造函数中初始化数据成员:

class MainWindow
{
    std::auto_ptr<int> pdoseIn;
    MainWindow ()
        : pdoseIn(new int)
    {
    }
};