1

我正在尝试编写一个小型应用程序,并且使用 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

感激地收到任何帮助或建议。

4

3 回答 3

3

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

#include <memory.h>

你应该写

#include <memory>

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

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

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

std::auto_ptr<int> pdoseIn;
MainWindow()
    : pdoseIn(new int)
{}
于 2012-04-03T05:05:41.110 回答
2

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

于 2012-04-03T04:58:30.690 回答
2

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

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

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

class MainWindow
{
    std::auto_ptr<int> pdoseIn;
    MainWindow ()
        : pdoseIn(new int)
    {
    }
};
于 2012-04-03T05:00:02.727 回答