0

我刚刚开始使用 C++,我已经遇到了问题。我正在尝试制作一个名为brushInput的QFile(来自QTCore)。它的意思是“期待一个声明”。我查了一下,它似乎是由语法问题引起的,但我在我的代码中没有看到。有没有班级都这样做。

#include <QtCore>

class Ink
{
    QFile *brushInput;

    brushInput = new QFile("x:\Development\InkPuppet\brush.raw");
};
4

4 回答 4

3

您不能在类定义中分配作业。但是,您可以在 C++11 的类定义中进行默认初始化:

class Ink
{
    QFile* brushInput = new QFile("x:\\Development\\InkPuppet\\brush.raw"); 
};

但是,通常我希望初始化进入构造函数:

class Ink
{
    QFile* brushInput;
public:
    Ink(): brushInput(new QFile("x:\\Development\\InkPuppet\\brush.raw")) {}
};
于 2013-08-24T23:44:16.937 回答
1

您不能在类内进行分配,只能进行初始化。因此,使用类的成员初始化器列表:

class Ink
{
    QFile *brushInput;
public:
    Ink() : brushInput(new QFile("x:\Development\InkPuppet\brush.raw"));
};
于 2013-08-24T23:45:03.303 回答
0

由于您显然是 C++ 新手,因此您需要了解一些入门知识:

  1. 在 C++ 中有两种源文件:头文件 (.h) 和源文件 (.cpp)。C++ 中的所有内容都必须声明和实现。这是两个不同的东西。一般规则是声明进入头文件,实现进入 .cpp 文件。

    在你的情况下:

    //ink.h file
    #ifndef INK_H    //this avoids multiple inclusion
    #define INK_H
    #include <QtCore>
    
    class QFile;  //let the compiler know the QFile is defined elsewhere
    
    class Ink
    {
        public:     //as a rule of thumb,
                    //always declare the visibility of methods and member variables
            Ink();  //constructor
            ~Ink(); //it is a good practice to always define a destructor
    
        private:
            QFile *brushInput;
    };
    #endif
    
    //.cpp file
    #include "ink.h"
    
    //implementation of the constructor
    Ink::Ink() :
        brushInput(new QFile("x:/Development/InkPuppet/brush.raw");  //you can use forward slashes; Qt will convert to the native path separators
    {}
    
  2. 避免在头文件中实现
    作为第二条规则,避免在头文件中实现,尤其是构造函数和析构函数。
    头文件中方法的实现称为内联方法(并且必须这样标记)。首先,避免使用它们,并尝试实现 .cpp 文件中的所有内容。当你对 C++ 比较熟悉时,就可以开始使用“更高级”的东西了。

于 2013-08-25T11:18:29.530 回答
0

这个:

brushInput = new QFile("x:\Development\InkPuppet\brush.raw");

是一个声明。语句(除了声明)只能出现在函数定义中,不能出现在类或文件范围内。

将语句放入函数定义(可能是构造函数)中决定了何时执行该语句。如果您认为它应该在创建对象时执行——好吧,这就是构造函数的用途。

于 2013-08-24T23:44:27.187 回答