C++”;期望声明”;
C++ "expected a declaration"
我刚开始使用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++的新手,因此需要了解一些入门知识:
-
在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 {}
-
避免在头文件中实现
第二条规则是,避免在头文件中实现,当然是构造函数和析构函数
头文件中方法的实现被称为内联方法(它们必须这样标记)。首先,避免使用它们,并尝试在.cpp文件中实现所有内容。当你更熟悉C++时,你可以开始使用"更高级"的东西。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 友元 LinkedQueue<T>;期望有声明
- C++”;期望声明”;
- 论据太少,期望发表声明
- 为什么Pascal Script期望在外部函数声明附近再加一个分号
- 错误:期望声明
- visual studio 2010 -智能感知:期望在c++中有一个声明