C++ 中常量属性的初始化构造函数错误
init constructor error for constant property in c++
我想成员初始化我的常量变量,并在类外的构造函数中编写一些代码。
编译器错误
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";
}
或者如果你愿意,将定义留在类中(在这种情况下它将是内联的(。
相关文章:
- 为什么std::vector和std::valarray初始化构造函数不同
- 初始化构造函数C++中结构的向量
- C++ 中常量属性的初始化构造函数错误
- 不正确的输出和变量未用Eclipse CDT初始化构造函数
- 如何使用嵌套初始化构造函数中的一维向量初始化矩阵
- 如何通过参数初始化构造函数中的数组?
- 是否有理由使用 malloc 初始化构造函数中的指针
- 如何在 c++ 中初始化构造函数中的二维数组
- 为什么初始化构造函数列表参数时会发生异常?
- 无法初始化构造函数
- 初始化构造函数的默认参数的优选方法是什么?
- 在C++17中使用空列表初始化构造函数时发生编译错误
- C++ 初始化构造函数初始化列表中的嵌套结构?
- 初始化构造函数c++中的向量
- g++ (GCC) 4.6.0 我有以下类,我正在尝试初始化构造函数的结构成员初始化列表
- 使用字符串文本初始化构造函数中的 std::array<char,x> 成员。海湾合作委员会错误?
- 初始化构造函数C++中函数的成员指针
- 在c++中初始化构造函数中的静态成员变量时出错
- memset()初始化构造函数中的对象
- 初始化构造函数C++中的成员向量