如何让一个带有方法的c++对象接受封闭类的参数

How to have a c++ object with a method that takes argument the enclosing class?

本文关键字:对象 c++ 参数 有方法 一个      更新时间:2023-10-16

我正试图弄清楚c++中是否有任何已知的模式/习惯用法可以用于我在这里要做的事情。类A必须由一个具有函数的对象组成,该函数的参数也必须是类型A。以下代码不编译,因为typeid不能用于常量表达式中。有什么建议吗?

#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T>
struct B { 
  int f(T& i) { cout << "Hellon"; } 
};
class A {
  B<typeid(A)> b;
};
int main()
{ 
  A k;
}

您声明的需求根本不需要模板,只需要一个正向声明:

#include <iostream>
class A; // forward declare A
struct B { 
  int f(A &i); // declaration only, definition needs the complete type of A
};
class A {
  B b;
};
int B::f(A &i) { std::cout << "Hellon"; } // define f()
int main()
{ 
  A k;
}

您正在寻找B<A> b;以下程序在g++4.4.3上编译时没有错误或警告。

#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T>
struct B {
  int f(T& i) { cout << "Hellon"; return 0; }
};
class A {
public:
  B<A> b;
};
int main()
{
  A k;
  return k.b.f(k);
}

注意:如果您使用模板只是为了避免前向声明,那么我的解决方案是错误的。但是,我将把它留在这里,以防您出于其他正当原因使用模板。