小编tou*_*nom的帖子

为什么要尝试两次找到析构函数?

我正在尝试以下代码:

GeneralTemplate.h

#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)

main.cpp中

#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)

c++ templates undefined-reference

6
推荐指数
1
解决办法
125
查看次数

错误:成员''的请求不明确

码:

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作为参数而未创建?

c++

6
推荐指数
0
解决办法
385
查看次数

返回的局部变量引用:为什么要警告?为什么不出错?

考虑一下代码:

int& getValue()
{
  int i = 10;
  return i;
}
Run Code Online (Sandbox Code Playgroud)

这会导致编译器警告:

警告:引用局部变量`i'返回

我理解警告的原因.我正在返回一个局部变量的引用,一旦我超出范围就会被销毁.

我的问题是:为什么甚至允许这样做?为什么编译器不会简单地给出错误而不是警告?

c++ warnings undefined-behavior

2
推荐指数
1
解决办法
757
查看次数