gpt4 book ai didi

c++ - gcc/g++ 错误 'implicitly-declared' 构造函数是 'deprecated' 的含义是什么?

转载 作者:行者123 更新时间:2023-12-04 08:08:09 26 4
gpt4 key购买 nike

我正在尝试解决将我的构建系统操作系统和 gcc 版本升级到 9 所产生的错误。我可以用下面的代码来演示它。

class Cl {
private:
float f;
public:
constexpr float GetF() const { return f; }
Cl& operator=(const Cl& other) {
f = other.GetF();
return *this;
}
Cl& operator=(const float& other) {
this->f = other;
return *this;
}
explicit constexpr Cl(const float& val) : f(val) {}
};

struct Sl {
float x, y;
Cl lcl;
constexpr Sl(const float &init_x, const float &init_y, const Cl &cl) : x(init_x), y(init_y), lcl(cl) {}

};

typedef struct Sl sdata;

int main()
{
const float fx = 30.30;
Cl c1(fx);
sdata s1(0, 0.0, c1);
return 0;
}
编译:
preetam@preetam-Precision-M4800 ~ $ g++-9 -Werror=deprecated-copy dp_test.cc 
dp_test.cc: In constructor ‘constexpr Sl::Sl(const float&, const float&, const Cl&)’:
dp_test.cc:22:101: error: implicitly-declared ‘constexpr Cl::Cl(const Cl&)’ is deprecated [-Werror=deprecated-copy]
22 | constexpr Sl(const float &init_x, const float &init_y, const Cl &cl) : x(init_x), y(init_y), lcl(cl) {}
| ^
dp_test.cc:8:6: note: because ‘Cl’ has user-provided ‘Cl& Cl::operator=(const Cl&)’
8 | Cl& operator=(const Cl& other) {
| ^~~~~~~~
cc1plus: some warnings being treated as errors`

错误的含义是什么?
我尝试按照此处的建议将以下内容添加到 Cl:
constexpr Cl(const Cl& other) {
f = other.GetF();
}
它导致了错误:
preetam@preetam-Precision-M4800 ~ $ g++-9 -Werror=deprecated-copy dp_test.cc 
dp_test.cc: In copy constructor ‘constexpr Cl::Cl(const Cl&)’:
dp_test.cc:10:9: error: member ‘Cl::f’ must be initialized by mem-initializer in ‘constexpr’ constructor
10 | }
| ^
dp_test.cc:5:9: note: declared here
5 | float f;
| ^
最后用以下复制构造函数修复:
constexpr Cl(const Cl& other) : f(other.f) {}

最佳答案

您正在为 lcl(cl) 使用复制构造函数虽然您没有定义一个,但您定义了一个用户定义的赋值运算符。您可以通过添加用户定义的构造函数来修复它:

class Cl {
private:
float f;
public:
constexpr float GetF() const { return f; }
constexpr Cl(const Cl& other) : f(other.f) { }
Cl& operator=(const Cl& other) {
f = other.GetF();
return *this;
}
Cl& operator=(const float& other) {
this->f = other;
return *this;
}
explicit constexpr Cl(const float& val) : f(val) {}
};

struct Sl {
float x, y;
Cl lcl;
constexpr Sl(const float &init_x, const float &init_y, const Cl &cl) : x(init_x), y(init_y), lcl(cl) {}

};

typedef struct Sl sdata;

int main()
{
const float fx = 30.30;
Cl c1(fx);
sdata s1(0, 0.0, c1);
return 0;
}
挑剔:“错误的含义是什么?”这不是错误而是警告。该项目可以编译并按预期运行,但当然,问题应该得到解决。

关于c++ - gcc/g++ 错误 'implicitly-declared' 构造函数是 'deprecated' 的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66115771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com