当我在不同的目标文件中使用专用模板时,链接时出现"多重定义"错误.我找到的唯一解决方案涉及使用"内联"功能,但它似乎只是一些解决方法.如何在不使用"inline"关键字的情况下解决这个问题?如果那不可能,为什么?
这是示例代码:
paulo@aeris:~/teste/cpp/redef$ cat hello.h
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <iostream>
template <class T>
class Hello
{
public:
void print_hello(T var);
};
template <class T>
void Hello<T>::print_hello(T var)
{
std::cout << "Hello generic function " << var << "\n";
}
template <> //inline
void Hello<int>::print_hello(int var)
{
std::cout << "Hello specialized function " << var << "\n";
}
#endif
Run Code Online (Sandbox Code Playgroud)
paulo@aeris:~/teste/cpp/redef$ cat other.h
#include <iostream>
void other_func();
Run Code Online (Sandbox Code Playgroud)
paulo@aeris:~/teste/cpp/redef$ cat other.c
#include "other.h"
#include "hello.h"
void other_func()
{
Hello<char> hc;
Hello<int> hi; …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种简单的方法来查找未初始化的类成员变量.
在运行时或编译时查找它们都可以.
目前我在类构造函数中有一个断点,并逐个检查成员变量.
我的理解是int变量将0自动初始化; 但事实并非如此.下面的代码打印一个随机值.
int main ()
{
int a[10];
int i;
cout << i << endl;
for(int i = 0; i < 10; i++)
cout << a[i] << " ";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我调用的类中Mat,我希望有一个函数,它将另一个函数作为参数.现在我有以下4个函数,但是在调用print()时遇到错误.第二行给了我一个错误,但我不明白为什么,因为第一行有效.唯一的区别是函数f不是类的成员Mat,而是f2.失败的是:error: no matching function for call to Mat::test( < unresolved overloaded function type>, int)'
template <typename F>
int Mat::test(F f, int v){
return f(v);
}
int Mat::f2(int x){
return x*x;
}
int f(int x){
return x*x;
}
void Mat::print(){
printf("%d\n",test(f ,5)); // works
printf("%d\n",test(f2 ,5)); // does not work
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?