[英]“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.