Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板类/函数中的交叉转发声明_C++_Templates - Fatal编程技术网

C++ 模板类/函数中的交叉转发声明

C++ 模板类/函数中的交叉转发声明,c++,templates,C++,Templates,我有两个头: 校长1: \ifndef CPPSH\u A\H #定义CPPSH_A_H 乙级;; 甲级{ 公众: 模板 无效函数1(){ b_->Function2(); } 模板 无效函数2(){ } 私人: B*B_; }; #endif//CPPSH_A_H 和校长2: #ifndef CPPSH_B_H #define CPPSH_B_H class A; class B { public: template<typename T> void Function1

我有两个头: 校长1:

\ifndef CPPSH\u A\H
#定义CPPSH_A_H
乙级;;
甲级{
公众:
模板
无效函数1(){
b_->Function2();
}
模板
无效函数2(){
}
私人:
B*B_;
};
#endif//CPPSH_A_H
和校长2:

#ifndef CPPSH_B_H
#define CPPSH_B_H
class A;
class B {
 public:
  template<typename T>
  void Function1() {
    a_->Function2<int>();
  }
  template<typename T>
  void Function2() {

  }
 private:
  A* a_;
};
#endif //CPPSH_B_H
\ifndef CPPSH\u B\H
#定义CPPSH_B_H
甲级;
B类{
公众:
模板
无效函数1(){
a->Function2();
}
模板
无效函数2(){
}
私人:
A*A;
};
#endif//CPPSH_B_H
您可以看到
a_
b_
都是不完整类型,对它的调用是invaild。 如果这两个类是普通类,我可以将
Test()
实现移动到源文件中,然后包含正确的头


但是由于模板类/函数必须在头文件中定义和声明它们的实现,如何处理这个问题?

您可以将两个头文件合并为一个,例如

// forward declaration
class B; 
class A {
 public:
  // member function template declaration
  template<typename T>
  void Function1();
  template<typename T>
  void Function2() {
  }
 private:
  B* b_;
};

class B {
 public:
  template<typename T>
  void Function1() {
    a_->Function2<T>();
  }
  template<typename T>
  void Function2() {
  }
 private:
  A* a_;
};

// member function template definition
template<typename T>
void A::Function1() {
  b_->Function2<T>();
}
//转发声明
乙级;;
甲级{
公众:
//成员函数模板声明
模板
void函数1();
模板
无效函数2(){
}
私人:
B*B_;
};
B类{
公众:
模板
无效函数1(){
a->Function2();
}
模板
无效函数2(){
}
私人:
A*A;
};
//成员函数模板定义
模板
void A::Function1(){
b_->Function2();
}

您可以将两个标题合并为一个标题;然后问题是
Test()
上的无限递归。这个例子似乎不太合适,让我来编辑一下您已经声明了四个不同的类:
A
A::B
B
,和
B::A
。“不是你想做的吗?”阿斯切普勒纠正了这个问题,谢谢你的指点。
// forward declaration
class B; 
class A {
 public:
  // member function template declaration
  template<typename T>
  void Function1();
  template<typename T>
  void Function2() {
  }
 private:
  B* b_;
};

class B {
 public:
  template<typename T>
  void Function1() {
    a_->Function2<T>();
  }
  template<typename T>
  void Function2() {
  }
 private:
  A* a_;
};

// member function template definition
template<typename T>
void A::Function1() {
  b_->Function2<T>();
}