返回C ++对象时,“没有用于初始化的匹配构造函数”

时间:2013-09-09 19:53:52

标签: c++ constructor llvm

我有一个简单的对象,我想在方法中返回一个对象。我知道使用的构造函数是有效的,因为它在其他地方使用。

return Color(red, blue, green);

此代码返回以下错误:No matching constructor for initialization of 'transitLib::Color'

然而,只需添加*new即可使事情发挥作用:

return *new Color(red, blue, green); //Valid, apparently.

知道为什么会产生这个错误吗?

附件是该类的完整代码

·H

class Color {

    float red;
    float blue;
    float green;

public:
    Color(float red, float blue, float green);
    Color(Color &color);

    Color colorByInterpolating(Color const& destinationColor, float fraction);

    bool operator==(const Color &other) const;
    bool operator!=(const Color &other) const;
    Color operator=(const Color &other);

    float getRed();
    float getBlue();
    float getGreen();
};

的.cpp

transitLib::Color::Color(float red, float blue, float green):red(red),blue(blue),green(green){}
transitLib::Color::Color(Color &color):red(color.red),blue(color.blue),green(color.green){}

Color transitLib::Color::colorByInterpolating(Color const& destinationColor, float fraction) {
    return Color(red + fraction * (destinationColor.red - red), blue + fraction * (destinationColor.blue - blue), green + fraction * (destinationColor.green - green));
}

bool Color::operator==(const Color &other) const {
    return other.red == red && other.blue == blue && other.green == green;
}

bool Color::operator!=(const Color &other) const {
    return !(other == *this);
}

Color Color::operator=(const Color &other) {
    red = other.red;
    blue = other.blue;
    green = other.green;

    return *this;
}

float transitLib::Color::getRed() {
    return red;
}

float transitLib::Color::getBlue() {
    return blue;
}

float transitLib::Color::getGreen() {
    return green;
}

1 个答案:

答案 0 :(得分:4)

按值返回时,正在复制(使用复制构造函数)。您正在尝试返回临时,它不能绑定到非const引用(这是您的复制构造函数作为参数)。

更改

Color(Color &color);

Color(const Color &color);