小编use*_*422的帖子

在C++中,为什么不能使用另一个类的模板类型来管理模板类成员函数?

换句话说,为什么编译正常:

template<typename Type>
class A{
  public:
    void f();
};

class B{
  friend void A<int>::f();
};

template<>
void A<int>::f(){
  B* var = new B();
}
Run Code Online (Sandbox Code Playgroud)

虽然这不是:

template<typename Type>
class A{
  public:
    void f();
};

template<typename Type> // B is now a templated class
class B{
  friend void A<Type>::f(); // Friending is done using B templated type
};

template<>
void A<int>::f(){
  B<int>* var = new B<int>(); // var is now declared using int as its templated type
}
Run Code Online (Sandbox Code Playgroud)

对于第二个代码片段,编译器(gcc 6.2,没有特殊标志)说:

main.cpp: In …
Run Code Online (Sandbox Code Playgroud)

c++ templates friend

25
推荐指数
1
解决办法
398
查看次数

为什么在初始化和调整对象向量时调用析构函数?

在我的程序中发生了一些事情,我无法找到它是否应该发生.如果是的话,我不明白为什么......

这是代码:

#include <iostream>
#include <vector>

using namespace std;

class A{
  public:
    A();
    ~A();
};

A::A(){
  cout << "creating" << endl;
}

A::~A(){
  cout << "deleting" << endl;
}

int main(void){
  vector<vector<A > > vec;

  vec.resize(5);
  for(int i = 0; i < 5; ++i){
    vec[i].resize(5);
  }

  cout << "END" << endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

creating
deleting
creating
deleting
creating
deleting
creating
deleting
creating
deleting
END
deleting
deleting
[..more deleting here]
Run Code Online (Sandbox Code Playgroud)

我理解为什么在"END"消息之后调用析构函数,但之前,我没有.我认为当向量调整大小时,类的构造函数被调用,但为什么是析构函数?

c++ vector

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

标签 统计

c++ ×2

friend ×1

templates ×1

vector ×1