【发布时间】:2011-09-18 14:36:25
【问题描述】:
如果我有以下代码(问题的简化版):
class TestA
{
public:
int A,B,C;
TestA(){A = 1; B = 5; C = 10;}
};
//This is a referencing class to allow for universal and consistent operations
class TestB
{
public:
int &A, &B, &C; //Note references
TestB(TestA &A) : A(A.A), B(A.B), C(A.C){}; //This is fine
TestB(TestC &C) : A(C.A), B(C.B), C(C.C){}; //This needs to be prototyped
};
//Similar class to TestA but in the main program would have...
//...many different and conflicting variables and has to be treated as stand alone
class TestC
{
public:
int A, B, C;
int Size;
void Function()
{
TestB B(*this); //This uses TestB. TestB cannot be prototyped.
//etc etc
}
};
我想知道,是否可以对基于初始化列表的构造函数进行原型化?
如果没有,有什么替代方案?请记住,引用必须立即初始化。
【问题讨论】:
-
“原型”的真正含义是什么?您是指需要单独的声明和定义,以便
TestC可用? -
ctors 中的“原型”初始化列表是什么意思?
-
TestC 将自身的副本传递给 TestB,以便 TestB 可以引用回 TestC。然后将一个 TestA 复制到另一个 TestB,允许两个类(TestA 和 TestC)相互操作,并传递给 TestB 期望函数,而无需向下转换或向上转换(这可能涉及切片,因此会出现问题)。
-
@SSight,你能不能不只是做
TestB(const TestC& t)来互相传递你的课程? -
TestB 预计会修改调用类。这只是问题的一个非常非常简单的版本。基本上原版都有模板类和子类,不想冒险切片,所以TestB基本上是通用的适配器类。