std :: shared_ptr<>中新的预期标识符

时间:2017-10-06 12:16:24

标签: c++ shared-ptr new-operator

我在'Serializer'类中使用共享指针时收到错误。

这是我的详细错误:

 client.h:28:52: error: expected identifier before new
 std::shared_ptr<Serializer> serializerObj2(new Serializer);
                                                ^
 client.h:28:52: error: expected , or .. before new

这是我的最小代码:

std::shared_ptr<Serializer> serializerObj2(new Serializer);

这是我的扩展代码:

#include "serializer.h" 
#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<thread>
#include<string>
#include<cstring>
#include<utility>
#include <boost/filesystem.hpp>
#include<memory>

namespace TCP
{    
class Client
{
public:
    void start();
private:

    int networkSocket=socket(AF_INET,SOCK_STREAM,0);
    std::shared_ptr<Serializer> serializerObj2(new Serializer);
    std::shared_ptr<Serializer> serializerObj=std::make_shared<Serializer>();

    bool checkConnection();
    std::pair<bool,std::string>getFile();
    void sendMessage();
    void setMessage();
}; 
}//closes namespace `

这是我的Serializer h文件:

#ifndef D_SERIALIZER_H
#define D_SERIALIZER_H
#include<iostream>
#include<arpa/inet.h>
#include<string>
namespace TCP
{
class Serializer
{

public:
    //sender
    void addIntToStream(int);
    void addStringToStream(std::string);
    void addCharToStream(char);
    std::pair<bool,const char*>getStream(size_t requestSize_);
    void delStream(size_t deleteSize_);

    //receiver
    void addByteToStream(const char*,size_t);
    std::pair<bool,int> retrieveIntFromStream();
    std::pair<bool,char> retrieveCharFromStream();
    std::pair<bool,std::string> retrieveStringFromStream(int);

    Serializer()
    {
        _stream="";
        _it=_stream.begin();
    }

private:
    std::string _stream;
    std::string::iterator _it;
};

}    //closes namespace
#endif

1 个答案:

答案 0 :(得分:3)

class Serializer
{
public:
    std::shared_ptr<Serializer> serializerObj2(new Serializer);

这是类中的变量声明
传统上,它们只能在构造函数中初始化。
但是,从C ++ 11开始,它们也可以使用

进行初始化
type var = value;

语法。你不能在那里使用括号,因为那将被解析 作为功​​能声明。所以改成它:

std::shared_ptr<Serializer> serializerObj2 = new Serializer;