在另一个类声明中创建类的对象时"Expected a type specifier"错误
"Expected a type specifier" error when creating an object of a class inside another class declaration
我有一个名为scratch的类,并使用scratch.h来声明它。
现在我在 scratch2.h 下有另一个名为 scratch2 的类,并希望创建一个 scratch 对象作为共享指针。
这是我在 scratch2 类声明中使用的语法:
std::shared_ptr<scratch> newObject(new scratch());
但是我收到此错误:Error: Expected type specifier
所以我尝试了这个:
std::shared_ptr<scratch> newObject2 = std::make_shared<scratch>();
这工作正常。谁能告诉我为什么第一个不起作用?
我的刮刮乐代码:
#ifndef _SCRATCH_
#define _SCRATCH_
#include <iostream>
class scratch {
private:
int _a;
float _b;
std::string _s;
public:
scratch();
scratch(int a, float b, std::string n);
~scratch();
};
#endif
和我的划痕2.h:
#ifndef _SCRATCH_2_
#define _SCRATCH_2_
#include "scratch.h"
#include <memory>
class scratch2 {
std::shared_ptr<scratch> newObject(new scratch()); // Expected a type specifier error occurs here
std::shared_ptr<scratch> newObject2 = std::make_shared<scratch>(); // works fine here
};
#endif
因为在声明类成员的上下文中:
std::shared_ptr<scratch> newObject(new scratch());
这最初将编译器视为类方法声明。C++的语法非常复杂。您可以查看整个声明并了解它试图执行的操作,但编译器一次解析一个关键字,并看到以下内容:
类型名称( ...
在类声明中,这开始看起来像类方法声明,这就是编译器尝试解析的内容,但失败了。
C++语言的正式规范在如何声明事物的主题上洒下了很多笔墨,同时注意到编译器技术的当前状态。
您需要使用编译器,并使用明确的替代语法:
std::shared_ptr<scratch> newObject = std::shared_ptr<scratch>(new scratch());
已通过 gcc 5.3 验证
在类定义中,只有两种方法可以初始化成员。您可以使用=
,也可以使用{}
。您不得使用()
:
struct foo {
int x = 4; // OK
int y{7}; // OK
int z(12); // error
};
诚然,在这种情况下,编译器错误是非常无益的。
相关文章:
- 对象声明中的模板"error: expected expression"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- Arduino无法编译名为SP:"Expected ')' before '(' token"的变量
- 为什么我的功能在使用 goto 时会给我带来"expected primary-expression before '}' token"?
- 为什么我会"error: expected expression"?
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- 错误消息"expected expression"....有人知道它为什么这么说吗?
- 由于"error C4430: missing type specifier - int assumed. Note: C++ does not support default-int",我现在无法编
- C++中的"expected unqualified-id"错误是什么?
- 我正在尝试创建一个枚举,但得到了"identifier expected error"
- 为什么我有"Expected type specifier error"?
- 默认模板参数结果为"expected type-specifier"
- 编译错误 C++ "was not declared in this scope" "expected type specifier"等
- Qt:"Expected type-specifier"出现在一台设备上,而不是另一台具有相同代码的设备上
- 在同一函数中"this declaration ahs no type specifier"和"expected a declaration"错误
- 在另一个类声明中创建类的对象时"Expected a type specifier"错误
- 在自定义类中实例化自定义类时出现"expected type-specifier"错误
- 编译函数模板时出现"expected nested-name-specifier"错误
- 编译器错误:"expected specifier-qualifier-list"
- 尝试从模板化类制作 .o 时"expected type-specifier"