【问题标题】:Instantiating an object in a namespace with a constructor whose defined in the same namespace. C++使用在同一命名空间中定义的构造函数实例化命名空间中的对象。 C++
【发布时间】:2013-05-22 21:52:22
【问题描述】:

在尝试为原始函数创建函数对象包装类时,我尝试在头文件的命名空间中定义并在源代码中声明它时遇到了多重定义错误。这工作正常,但是当我尝试基于命名空间中的原始函数实例化一个函数对象时,我得到了错误。

空格.h

#ifndef SPACE_H
#define SPACE_H
namespace fobj{

class function_object
{
public:
    function_object(double (*f)(double)) { raw_function = f; }
    double operator()(double x) {return raw_function(x); }
private:
    double (*raw_function)(double);
};

}

namespace fraw {

double raw(double x);

/** below is the trouble maker. When removed, the error doesn't occur. But also,
    when the above is instead declared inline, the error doesn't occur either. **/

fobj:: function_object obj( raw ); 

}
#endif

空间.cpp

#include "space.h"

double fraw:: raw(double x) { return x; }

main.cpp

#include <iostream>
#include "space.h"

int main()
{
    std::cout<< fraw::raw(1.5)<<std::endl;
    std::cout<< fraw::obj(2.5)<<std::endl;
    return 0;
}

【问题讨论】:

    标签: c++ header namespaces multiple-definition-error


    【解决方案1】:

    fobj:: function_object obj( raw ); 是一个定义 - 在多个翻译单元中包含标题会破坏一个定义规则。将变量声明为 extern 并将其定义在单个实现文件中。

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2012-06-13
      • 2017-05-31
      • 2013-05-17
      • 2013-03-25
      • 1970-01-01
      相关资源
      最近更新 更多