简体   繁体   English

C++ 没有可行的构造函数复制类型的变量

[英]C++ no viable constructor copying variable of type

I am getting the following error message:我收到以下错误消息:

main.cpp: No viable constructor copying variable of type 'communal' main.cpp:没有可行的构造函数复制“公共”类型的变量

On the second constructor, communal( const T& instance ) , the following message is given:在第二个构造函数communal( const T& instance ) ,给出了以下消息:

data.h: Candidate constructor not viable: no known conversion from 'communal' to 'const int &' for 1st argument data.h:候选构造函数不可行:第一个参数没有从“公共”到“const int &”的已知转换

The conversion appears to be going backwards.转换似乎正在倒退。 I want the conversion to go from const int& to communal.我希望转换从 const int& 到公共。 Is there a way to get implicit conversion to work here?有没有办法让隐式转换在这里工作? Thanks for any help.谢谢你的帮助。

main.cpp:主.cpp:

communal<int> test_communal1 = 123; // Implicit initialization triggers error

data.cpp:数据.cpp:

template<typename T>
struct communal : general_type::communal<T>
{
    using super = general_type::communal<T>;

    communal() : super( nullptr ) {}
    communal( const T& instance ) : super( new T( instance ) ) {}
    communal( const T* instance ) : super( new T( instance ) ) {}
    communal( communal<T>& instance ) : super( instance ) {}
    communal( communal<T>* instance ) : super( instance ) {}

    ~communal()
    {
        this->counter->deallocate( [this]()
        {
            delete this->counter;
            delete this->instance;
        });
    }
};

I figured out the solution to this.我想出了解决这个问题的办法。 My intention was to get the following converting constructor to work communal( const T& instance ) .我的目的是让以下转换构造函数工作communal( const T& instance ) I made the mistake of leaving off const for my copy constructors.我犯了一个错误,为我的复制构造函数保留了 const。 For some reason, it was deducing to use the faulty copy constructor along with potential conversion from communal<int> to const int& .出于某种原因,推断使用错误的复制构造函数以及从communal<int>const int&潜在转换。 In adding const to the constructor, it fixed the problem.将 const 添加到构造函数中,它解决了这个问题。 Though, it does seem to be a bug that it would not prioritize using the converting constructor first.尽管如此,它似乎确实是一个错误,它不会优先使用转换构造函数。 Maybe with more studying this problem, I could get a deeper understanding to why it prioritized the other constructor over the converting constructor.也许通过更多地研究这个问题,我可以更深入地理解为什么它优先于其他构造函数而不是转换构造函数。 Though, that will have to wait for now.不过,这将不得不等待现在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM