gpt4 book ai didi

c++ - C++中常量属性的初始化构造函数错误

转载 作者:行者123 更新时间:2023-11-27 23:44:03 25 4
gpt4 key购买 nike

我想为我的 const 变量添加成员初始值设定项,并在类外的构造函数中编写一些代码。

编译错误

test.cpp:13:4: error: redefinition of 't'
t::t(int n){
^
test.cpp:7:5: note: previous definition is here
t(int n) : num(n),z(n) {}
^
test.cpp:13:4: error: constructor for 't' must explicitly initialize the const
member 'num'
t::t(int n){
^
test.cpp:9:15: note: declared here
const int num;
^
test.cpp:21:7: error: no matching constructor for initialization of 't'
t ob(4);
^ ~
test.cpp:4:7: note: candidate constructor (the implicit copy constructor) not
viable: no known conversion from 'int' to 'const t' for 1st argument
class t

代码

#include<iostream>
using namespace std;

class t
{
public:
t(int n) : num(n),z(n) {}
private:
const int num;
int z;
};

t::t(int n){
cout<<"TEST";
}

int main()
{
t ob(4);
return 0;
}

最佳答案

您已经定义了同一个构造函数两次。
这里:

t(int n) : num(n),z(n) {}

在这里:

t::t(int n){
cout<<"TEST";
}

要解决此问题,您可以将其更改为:

t(int n);

和:

t::t(int n) : num(n),z(n) {
cout<<"TEST";
}

如果您愿意,也可以将定义保留在类中(在这种情况下它将是内联的)。

关于c++ - C++中常量属性的初始化构造函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52140609/

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