C ++:使用main中定义的函数的类方法

时间:2013-12-02 21:40:59

标签: c++ scope

所以我有一个班级:

class MyClass
public:
    printSomeStuff() { //Including implementation here to save space
        print(data);
    }

private:
    int data;

一个主程序,外部定义了模板函数:

template<typename T>
void print(T val) {
    cout << val;
}

int main() {
    MyClass a;
    a.printSomeStuff();
}

我的想法是我可以在其他地方移动MyClass并且没问题,但是需要根据场景定义新的print函数。通常情况下,这只是cout

但是,如果我尝试实际使用这种编码方式,则会收到错误,因为MyClass.cpp中未定义print

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

将模板定义放在自己的头文件中,并将其包含在类实现文件中。

也就是说,有了像打印这样简单的东西,完全可以在printSomeStuff方法中轻松完成。额外的间接并没有真正为你买任何东西。

答案 1 :(得分:3)

您应该将print()函数移动到标题(和合适的名称空间)中,并将其包含在需要它的翻译单元中,例如:

// print.h
#ifndef INCLUDED_PRINT
#define INCLUDED_PRINT
#include <iostream>
namespace utilities {
    template <typename T>
    void print(T const& val) {
        std::cout << val;
    }
}
#endif

然后,您可以将此标题包含在使用它的翻译中,例如

// MyClass.h
#ifndef INCLUDED_MYCLASS
#define INCLUDED_MYCLASS
#include "print.h"

class MyClass
public:
    printSomeStuff() { //Including implementation here to save space
        utilities::print(data);
    }

private:
    int data;
};
#endif

答案 2 :(得分:0)

定义打印模板的标题必须可以从定义MyClass的标题中访问,但不一定是来自main,因此您可以将其移动到单独的标题并将其包含在MyClass.hpp甚至MyClass中。 CC

相关问题