假设我有一个 POD 类型的结构。
// A.hpp
//struct is of POD type
struct s {
int x;
double y;
};
然后我让这个结构成为 A 类的私有(private)成员
// A.hpp
class A{
s my_struct;
int size;
public:
A(int, double, int);
};
现在我想使用构造函数初始化类,我还想初始化 my_sruct。
我目前的情况是
// A.cpp
A::A(int x_, double y_, int size_):my_struct(x_, y_), size(size_){}
// main.cpp
A a( 4, 6.6, 7); // this is how I try to instantiate the object
但是我得到错误提示
error: no matching function for call to 's::s(int&, double&)'
我可以通过在 struct 中放置一个构造函数来解决它。但我认为对于 POD,我们不需要这样做。我在这里遗漏了什么吗?
最佳答案
改变这个:
A::A(int x_, double y_, int size_):my_struct(x_, y_), size(size_){}
为此:
A::A(int x_, double y_, int size_):my_struct({x_, y_}), size(size_){}
偶数(没有 QPaystaxes 所说的括号):
A::A(int x_, double y_, int size_):my_struct{x_, y_}, size(size_){}
最小的例子:
struct s {
int x;
double y;
};
class A{
s my_struct;
int size;
public:
A(int, double, int);
};
A::A(int x_, double y_, int size_):my_struct({x_, y_}), size(size_){}
int main() {
A a( 4, 6.6, 7);
return 0;
}
编译:
C02QT2UBFVH6-lm:~ gsamaras$ g++ -std=c++11 main.cpp
C02QT2UBFVH6-lm:~ gsamaras$
否则,您可以关注此answer .
关于c++ - 如何通过 C++ 中构造函数的初始化列表来初始化类的私有(private)结构成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38964081/