C++”;期望声明”;

C++ "expected a declaration"

本文关键字:声明 期望 C++      更新时间:2023-10-16

我刚开始使用C++,已经遇到了一个问题。我正在尝试制作一个名为brushInput的QFile(来自QTCore)。上面写着"期待一份声明"。我查过它,它似乎是由语法问题引起的,但我在代码中没有看到。上课和不上课都这样做。

#include <QtCore>
class Ink
{
    QFile *brushInput;
    brushInput = new QFile("x:DevelopmentInkPuppetbrush.raw");
};

类定义中不能有赋值。您可以在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")) {}
};

不能在类内部进行赋值,只能进行初始化。因此,使用类的成员初始值设定项列表:

class Ink
{
    QFile *brushInput;
public:
    Ink() : brushInput(new QFile("x:DevelopmentInkPuppetbrush.raw"));
};

这:

brushInput = new QFile("x:DevelopmentInkPuppetbrush.raw");

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

将语句放入函数定义(可能是构造函数)中,可以确定何时执行该语句。如果您认为应该在创建对象时执行它,那么构造函数就是这样做的。

由于您显然是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++时,你可以开始使用"更高级"的东西。