我正在尝试以下代码:
#ifndef _GENERATEMPLATE_H_
#define _GENERATEMPLATE_H_
#include <iostream>
template <class T>
class GeneralTemplate
{
public:
GeneralTemplate();
GeneralTemplate(const GeneralTemplate &g);
~GeneralTemplate();
GeneralTemplate& operator= (GeneralTemplate const& g);
template <class M>
void arbitraryFunction(const M &m);
};
#endif
Run Code Online (Sandbox Code Playgroud)
#include "GeneralTemplate.h"
#include <iostream>
int main()
{
GeneralTemplate<int> gInt;
gInt.arbitraryFunction(2.3);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我没有任何类模板的成员函数的实现.但那不是问题.我知道怎么做!如果我尝试编译main.cpp,我应该得到一个链接错误,这就是我得到的.问题是为什么它试图找到两次析构函数(下面的两行错误).
$g++ main.cpp
/tmp/cckrdPCs.o: In function `main':
main.cpp:(.text+0x13): undefined reference to `GeneralTemplate<int>::GeneralTemplate()'
main.cpp:(.text+0x34): undefined reference to `void GeneralTemplate<int>::arbitraryFunction<double>(double const&)'
main.cpp:(.text+0x45): undefined reference to `GeneralTemplate<int>::~GeneralTemplate()'
main.cpp:(.text+0x61): undefined reference to `GeneralTemplate<int>::~GeneralTemplate()'
collect2: ld returned …Run Code Online (Sandbox Code Playgroud) 码:
class A1 {};
class A2 {};
template <class M>
class Base
{
public:
void func(M &m) const {}
};
class Derived : public Base<A1>, public Base<A2>
{};
int main()
{
Derived d;
A1 a1;
d.func(a1);
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
AmbiguousFunction.cpp: In function \u2018int main()\u2019:
AmbiguousFunction.cpp:19: error: request for member \u2018func\u2019 is ambiguous
AmbiguousFunction.cpp:9: error: candidates are: void Base<M>::func(M&) const [with M = A2]
AmbiguousFunction.cpp:9: error: void Base<M>::func(M&) const [with M = A1]
Run Code Online (Sandbox Code Playgroud)
为什么我会收到此错误?有两种风格的功能,一种是A1,另一种是使用A2作为参数而未创建?
考虑一下代码:
int& getValue()
{
int i = 10;
return i;
}
Run Code Online (Sandbox Code Playgroud)
这会导致编译器警告:
警告:引用局部变量`i'返回
我理解警告的原因.我正在返回一个局部变量的引用,一旦我超出范围就会被销毁.
我的问题是:为什么甚至允许这样做?为什么编译器不会简单地给出错误而不是警告?