【问题标题】:C++ class copy constructor has no matching functionC++类拷贝构造函数没有匹配函数
【发布时间】:2016-07-11 19:25:54
【问题描述】:

我正在尝试编写一个类Core,它的成员变量是一个指针。复制构造函数是Core(Core& x) 而不是Core(const Core& x)

Core有一个成员函数Core Core::new_core (int * ptr),我尝试构造Core new_core= core.new_core(ptr);时代码有问题,请看下面的代码和错误信息。

#include<iostream>

class Core
{
    private:
    int* a;

    public:
    Core(int* in) {a=in;}
    Core(Core& x) {a = x.data();}

    inline const int * data() const {return a;}
    inline       int * data()       {return a;}

    Core new_core (int * ptr)
    {
        Core b(ptr);
        return b;
    }
};

using namespace std;

int main()
{
    int ptr[3]= {1,2,3};
    Core core(ptr);
    Core new_core= core.new_core(ptr);
    cout<< new_core.data() <<endl;
    return 0; 
}

错误信息:

main.cpp:在函数'int main()'中:

main.cpp:30:37: 错误:没有匹配函数调用‘Core::Core(Core)’

Core new_core= core.new_core(ptr);
                                 ^

main.cpp:30:37: 注意:候选人是:

main.cpp:12:6: 注意:Core::Core(Core&)

 Core(Core& x) { a = x.data() ;}
 ^

main.cpp:12:6: 注意:参数 1 没有从‘Core’到>‘Core&’的已知转换

main.cpp:10:6: 注意:Core::Core(int*)

 Core(int* in) {a=in;}
 ^

main.cpp:10:6: 注意:没有已知的参数 1 从“核心”到 'int*'

我可以通过替换轻松解决问题

Core(Core& x) { a = x.data() ;}

Core(const Core& x) { a = const_cast<int* > ( x.data() ) ;}, 

有没有更好的方法来解决这个问题而不使用 const_cast?

我想保持int* a 不公开,并保持以下两行:

inline const int * data() const {return a;}
inline       int * data()       {return a;}

谢谢。

【问题讨论】:

  • 这真的取决于你想让这个类做什么。鉴于它只引用外部数据,int * data() 不是const 有意义吗?即int * data() const;.
  • 谢谢你,juanchopanza。我举了一个太笼统的例子。在我的实际应用程序中,Core 是一个派生类, const int * data() const 来自基类,我无法更改。我想我必须使用 Core(const Core& x) 来解决问题?
  • 您的问题是非常量右值引用不能绑定到临时值。但是右值引用可以。有一个答案(现已删除)几乎是正确的......
  • 顺便说一句,如果我使用:Core core_a(ptr);Core core_b( core_a);,代码可以正常工作。为什么我不能使用Core new_core( core.new_core(ptr) );
  • 我明白了,非常感谢。

标签: c++ pointers constructor constants


【解决方案1】:

这里的问题是new_core 返回一个临时的Core。当你在

中使用它时
Core new_core= core.new_core(ptr);

编译器调用复制构造函数,但它无法绑定到该临时对象,因为它需要一个引用。为了解决这个问题,我们可以将复制构造函数更改为采用const Core&amp;,它可以绑定到临时文件并允许您进行复制。

在这个例子中,为了绕过constconst_cast的使用,我们可以直接访问类成员:

Core(const Core& x) : a(x.a) {}

【讨论】:

  • 非常感谢,这真的很有帮助。我还有一个问题,在我的真实示例中,Core 是一个模板驱动的类,而int * a 是基于模板的类。当我需要访问a时,我总是需要使用this-&gt;a,看来我不能使用:Core(const Core&amp; x) : this-&gt;a(x.a) {}
  • @HaoShi 这听起来像基类需要有一个适当的复制构造函数。如果您可以在您的问题中提供minimal reproducible example,我可能会为您提供进一步的帮助。
  • 感谢内森奥利弗!我明白了,我可以通过在基类中编写一个适当的复制构造函数来解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 2018-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多