2016-02-13 94 views
3

在寻找二叉树实现的示例时,我注意到代码中提供了一些奇怪的东西here。在节点结构的构造函数一个非指针类型的变量被分配给一个指针类型。C++,将非指针类型赋值给模板类的成员指针

它编译得很好(我正在使用GCC 5.3.0)。而让我感到困惑的是编译依赖于其他构造函数的参数,val

它在类中的方法没有效果,只是在构造函数:

我越来越
template <typename T> 
class Test { 
    Test* testPtr; 

    void testMethod(T t, Test<T> notAPointer) { // OK 
     this->testPtr = notAPointer; 
    } 

    void testMethod(Test<T> notAPointer) {  // OK 
     this->testPtr = notAPointer; 
    } 

    Test(T t, Test<T> notAPointer) {   // OK 
     this->testPtr = notAPointer; 
    } 

    Test(Test<T> notAPointer) {     // compilation error 
     this->testPtr = notAPointer; 
    } 
}; 

的编译错误是:

invalid constructor; you probably meant ‘Test (const Test&)’

这是为什么发生?标准中描述的这种行为在哪里?

+0

我认为这是一个错字。它编译得很好,因为所调用的构造函数没有被调用。 – cpplearner

+0

构造'notAPointer'参数时调用哪个构造函数? – emlai

+0

您的构造函数的问题与指针分配或任何伴随问题完全无关。你会得到与空的构造函数体相同的错误。复制构造函数无法通过值接收其参数 - 这就是它的全部内容,而这正是您的编译器试图告诉您的。 – AnT

回答

3

您最后的构造函数是copy constructor。禁止有一个拷贝构造函数按值传递它的参数,否则你会以无限递归结束。

你得到的错误是类似于

struct Foo 
{ 
    Foo(Foo); 
}; 

Live on Coliru

更确切地说,根据标准:

12.8/2复制和移动类对象[class.copy ]

A non-template constructor for class X is a copy constructor if its first parameter is of type X& , const X& , volatile X& or const volatile X& , and either there are no other parameters or else all other parameters have default arguments (8.3.6). [ Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.

其他构造函数/成员函数似乎没有问题,因为它们没有实例化,并且代码在语法上是正确的(理论上,Test<T>对于某些专业化可能具有转换运算符到T*,并且编译器在实例化之前无法检查)。然而,拷贝构造函数必须有一个确定的形式,这是由编译器强制执行的。

1

你所有的例子都是无效的。当您尝试实例化任何方法,你会得到一个编译错误:

template <typename T> 
struct Test { 
    Test* testPtr; 

    void testMethod(Test<T> notAPointer) { 
     this->testPtr = notAPointer; 
    } 
}; 

int main() { 
    Test<int> t1, t2; 
    t1.testMethod(t2); // This line will cause the error. 

    return 0; 
} 

prog.cpp: In instantiation of 'void Test::testMethod(Test) [with T = int]': prog.cpp:16:18: required from here prog.cpp:9:23: error: cannot convert 'Test' to 'Test*' in assignment this->testPtr = notAPointer; ^