在另一个类声明中创建类的对象时"Expected a type specifier"错误

"Expected a type specifier" error when creating an object of a class inside another class declaration

本文关键字:Expected specifier 错误 type 对象 声明 另一个 创建      更新时间:2023-10-16

我有一个名为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
};

诚然,在这种情况下,编译器错误是非常无益的。

相关文章: