我正在尝试运行以下程序,但它会生成编译错误:
#ifndef TEMPLATE_SUM_H_
#define TEMPLATE_SUM_H_
template<typename T>
class sum
{
public:
sum() {
val_1 = 0;
val_2 = 0;
}
sum(T a, T b) {
val_1 = a;
val_2 = b;
}
friend std::ostream& operator<<(std::ostream &, const sum<> &);
private:
T val_1, val_2;
T result() const;
};
#endif
Run Code Online (Sandbox Code Playgroud)
源文件:
include <iostream>
#include "inc/sum.h"
template<typename T>
T sum<T>::result() const {
return (val_1 + val_2);
}
template<typename T>
std::ostream& operator<<(std::ostream& os, const sum<T>& obj) {
//std::ostream& operator<<(std::ostream& os, sum<T>& obj) {
os << obj.result();
return os;
}
int main()
{
sum<int> int_obj(15, 15);
sum<float> float_obj(5.2, 3.5);
std::cout << "result of int = " << int_obj << std::endl;
std::cout << "result of float = " << float_obj << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用g ++(4.4.3)进行编译会产生以下错误:
In file included from template.cpp:2:
inc/sum.h:18: error: wrong number of template arguments (0, should be 1)
inc/sum.h:5: error: provided for ‘template<class T> class sum’
template.cpp: In function ‘std::ostream& operator<<(std::ostream&, const sum<T>&) [with T = int]’:
template.cpp:20: instantiated from here
template.cpp:5: error: ‘T sum<T>::result() const [with T = int]’ is private
template.cpp:12: error: within this context
template.cpp: In function ‘std::ostream& operator<<(std::ostream&, const sum<T>&) [with T = float]’:
template.cpp:21: instantiated from here
template.cpp:5: error: ‘T sum<T>::result() const [with T = float]’ is private
template.cpp:12: error: within this context
Run Code Online (Sandbox Code Playgroud)
1)有人可以帮我识别错误吗?另请提供一些链接,我可以在其中找到有关如何在c ++中使用模板的简要绝对详细信息.
2)我读到在头文件中声明的模板化的func/classes,并且单独定义的内容容易出现链接错误.任何人都可以解释/详述吗?在上面的例子中是否有可能链接错误?
声明如下:
"如果在.h文件中声明模板或内联函数,请在同一文件中定义.这些结构的定义必须包含在使用它们的每个.cpp文件中,否则程序可能无法在某些构建配置中链接 ".
这个例子可以用一些更简单的方式完成,不需要使用重载操作符等.但我正在尝试学习/练习模板和试验一些功能.
您需要为friend函数声明提供单独的模板定义:
template<typename U>
friend std::ostream& operator<<(std::ostream &, const sum<U> &);
Run Code Online (Sandbox Code Playgroud)
friend声明不会继承封闭类的模板参数.