我有一个名为 scratch 的类,并使用 scratch.h 来声明它。
现在我在 scratch2.h 下有另一个名为 scratch2 的类,我想创建一个 scratch 对象作为共享指针。
这是我在 scratch2 类声明中使用的语法:
std::shared_ptr<scratch> newObject(new scratch());
但我收到此错误:错误:预期的类型说明符
所以我尝试了这个:
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 验证
关于c++ - 在另一个类声明中创建一个类的对象时出现 "Expected a type specifier"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35762196/