-1

我想通过另一个类的构造函数传递一个类的引用实例。现在我不能这样做,因为我陷入了语法错误。我尝试了几个小时,但我学到了很多东西(比如循环依赖或前向声明),但实际上并不能解决我的问题。我有这样的文件:被类构造函数和初始化列表困惑,怀疑循环依赖

Project.h(Project类的构造函数传递的缓冲区类的一个实例参考)

Project.cpp

Buffer.h

Buffer.cpp

abo有四个文件在我的问题中是积极的(我的猜测)。

这里是Project.h内容:

#include<string> 
#include<regex> 
#include<iostream> 
#include<vector> 
#include "Buffer.h" 

using namespace boost::filesystem; 

#ifndef PROJECT_H 
#define PROJECT_H 

class Project(Buffer & buffer_param) : bufferObj(buffer_param) 
{ 

    Buffer& bufferObj; 

public: 
    Filer& filer; 

    std::string project_directory; 
    void createList(std::vector<std::string> list_title); 
}; 

#endif 

这里是project.cpp内容:

#include<string> 
#include<regex> 
#include<iostream> 
#include<vector> 
#include<boost\filesystem.hpp> 

#include "Project.h" 


using namespace boost::filesystem; 


void Project::createList(std::vector<std::string> list_title) 
{ 
    //this->filer.createFile(); 
} 

Buffer.h

#include<string> 
    #include<map> 


    #ifndef BUFFER_H 
    #define BUFFER_H 

    class Buffer 
    { 
     std::map<std::string, std::string> storage_str; 

     void setValueString(std::string key, std::string value); 
     std::string getValueString(std::string key); 
    }; 

    #endif 

Buffer.cpp

#include<string> 
#include<map> 
#include "Buffer.h" 


void Buffer::setValueString(std::string key, std::string value) 
{ 
    this->storage_str[key] = value; 
} 

问题:

,而没有经过缓冲的项目构造,一切完美,但只要我开始通过它的一个实例,错误抛出:

Project.h文件的所有错误:

error C2143: syntax error : missing ')' before '&' 
error C2143: syntax error : missing ';' before '&' 
error C2079: 'Buffer' uses undefined class 'Project' 
error C2059: syntax error : ')' 
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 
error C2530: 'buffer_param' : references must be initialized 
error C2143: syntax error : missing ';' before ':' 
error C2448: 'bufferObj' : function-style initializer appears to be a function definition 

错误的Project.cpp文件:

error C2027: use of undefined type 'Project' 
    see declaration of 'Project' 
+1

'类项目(缓冲液buffer_param)'!?一个构造函数(带或不带init.list)与全班一样 – deviantfan 2015-03-31 23:01:59

+0

有什么问题?是的(我更新了这个问题,不得不在项目类的文件中输入错误) – 2015-03-31 23:03:23

+1

正如我刚刚添加的,你将混淆/混合构造函数与整个类。构造函数是一个类方法,类似于createList – deviantfan 2015-03-31 23:04:37

回答

1

要详细说明,而不是对deviantfan的评论,这

class Project(Buffer & buffer_param) : bufferObj(buffer_param) 
{ 
    ... 

应该是这样的:

class Project 
{ 
public: 
    Project(Buffer & buffer_param) : bufferObj(buffer_param) 
    { 
    } 

private: 
    ... 
+0

谢谢。它确实有效。但是有一个问题,使用这种类型的头文件声明,那么我的'Project.cpp'中不能包含'Project :: Project(){..}',是的?因为它抛出一个错误,即“Project :: Project()'已经有一个主体。看来我应该在头文件中完成构造函数的所有工作? – 2015-03-31 23:22:39

+1

@MostafaTalebi你可以(也应该)把你的构造函数的内容放在cpp文件中。但是,如果你这样做,它不能同时在头文件中。只有两个文件中的一个。 – deviantfan 2015-03-31 23:37:04