【问题标题】:Converting Constructor C++转换构造函数 C++
【发布时间】:2023-03-25 05:56:01
【问题描述】:

大家好,我写了这门课……

struct TestStruct {
int a;
TestStruct(int pA) : a(pA){};
};

template <typename T> class ClassA {
public:
 ClassA() : mTestStruct(sizeof(T)) {}

 ClassA(T *ptr) : mTestStruct(sizeof(T)){};

 ClassA(T param) : mTestStruct(sizeof(T)){};

 ClassA(ClassA<T> &p){};

private:
 TestStruct mTestStruct;
 ClassA<T> &operator=(T *ptr) { return *this; };
};

并且想做这样的事情。 (我认为它被称为转换构造函数。)

    ClassA<long> p = new long;

但我明白了。 我用 -std=c++14 编译它

no viable constructor copying variable of type 'ClassA<long>'

顺便说一句,这个工作......

ClassA<long> p(new long)

有什么想法吗?

已编辑:好的,这是我用来重现错误消息的代码。

【问题讨论】:

标签: c++ templates constructor


【解决方案1】:
ClassA<long> p(new long);

调用ClassA构造函数,该构造函数将long 作为参数(T=long)。

ClassA<long> p = new long;

尝试使用从longClassA复制构造函数将新的long 分配给p,这当然不存在,因此不能使用。 p>


您需要在ClassA 中创建一个复制构造函数,该构造函数将&amp;long 作为复制变量,类似于:

ClassA(const T &obj)
{
    // do what you want to happen in the copy constructor
}

【讨论】:

  • 关于this = ClassA(obj)this是一个常量指针,不能赋值。
  • 但是为什么&amp;long。我正在分配一个指向 long 而不是 long 值的指针
猜你喜欢
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 2013-12-27
  • 2014-02-24
  • 1970-01-01
相关资源
最近更新 更多