[英]“Expected a type specifier” error when creating an object of a class inside another class declaration
我有一个名为scratch的类,并已使用scratch.h对其进行了声明。
现在我有下scratch2.h另一个类称为scratch2,想从头开始创建一个对象作为共享指针 。
这是我在scratch2类声明中使用的语法:
std::shared_ptr<scratch> newObject(new scratch());
但我收到此错误: Error: Expected type specifier
所以我尝试这样做:
std::shared_ptr<scratch> newObject2 = std::make_shared<scratch>();
效果很好。 谁能告诉我为什么第一个不工作?
我的scratch.h代码:
#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
和我的scratch2.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
};
诚然,这种情况下的编译器错误是毫无帮助的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.