从构造函数初始化结构
Initializing a struct from a constructor
我又开始写c++了,我真的有点生疏了。我有一种感觉,如果我知道如何正确地表达,我就能很快找到我的问题的答案,但我还是很感激你的帮助。
sanitycheck.cpp:
#include <string>
using namespace std;
typedef struct STR_1 {
int val_a, val_b;
STR_1 (int a, int b)
{ val_a = a; val_b = b; }
} STR_1;
typedef struct STR_2{
string name;
STR_1 myStr1;
STR_2 (string n, STR_1 s)
{ name=n; myStr1 = s; }
} STR_2;
int main(){
return 0;
} // end main
当我尝试用g++ -o sanitycheck ./test/sanitycheck.cpp
编译时,我得到以下内容,
./test/sanitytest.cpp: In constructor ‘STR_2::STR_2(std::string, STR_1)’:
./test/sanitytest.cpp:25:3: error: no matching function for call to ‘STR_1::STR_1()’
{ name=name; myStr1 = &s; }
^
./test/sanitytest.cpp:25:3: note: candidates are:
./test/sanitytest.cpp:11:3: note: STR_1::STR_1(int*, int*)
STR_1 (int *a, int *b)
^
./test/sanitytest.cpp:11:3: note: candidate expects 2 arguments, 0 provided
./test/sanitytest.cpp:7:16: note: STR_1::STR_1(const STR_1&)
typedef struct STR_1 {
^
./test/sanitytest.cpp:7:16: note: candidate expects 1 argument, 0 provided
./test/sanitytest.cpp:25:23: error: no match for ‘operator=’ (operand types are ‘STR_1’ and ‘STR_1*’)
{ name=name; myStr1 = &s; }
^
./test/sanitytest.cpp:25:23: note: candidate is:
./test/sanitytest.cpp:7:16: note: STR_1& STR_1::operator=(const STR_1&)
typedef struct STR_1 {
^
./test/sanitytest.cpp:7:16: note: no known conversion for argument 1 from ‘STR_1*’ to ‘const STR_1&’
我不清楚的一件事是为什么STR_2
的STR_1 myStr1;
首先需要调用STR_1
构造函数?我不能用
int main()
{
STR_1 bob = STR_1(5,6);
STR_2 tom = STR_2('Tom',bob);
return 0;
}
谢谢!
除非从评论中的链接到OP中还不清楚:这里,
typedef struct STR_2{
string name;
STR_1 myStr1;
STR_2 (string n, STR_1 s) // here the myStr1 default constructor is called
{ name=name; myStr1 = s; }
} STR_2;
要求STR_1
是默认可构造的。为了解决这个问题,必须在构造函数的初始化列表中构造成员STR_1 myStr1;
:
STR_2 (string n, STR_1 s) : name(n), myStr1(s) {}
演示调用编译器生成的STR_1
的复制构造函数,而不是默认构造函数(通过提供自定义构造函数来抑制其自动生成)。
另一个选择是使用指向STR_1
:
typedef struct STR_2{
string name;
std::unique_ptr<STR_1> myStr1;
STR_2 (string n, STR_1 s)
{ name=name; myStr1 = std::make_unique<STR_1>(s); } //just for the sake of explanation
//again, this would be better
//done in the initializer list
} STR_2;
然而,只有在有充分理由的情况下,我才会放弃第一种选择。
相关文章:
- 多成员Constexpr结构初始化
- 为什么用结构初始化数组需要指定结构名称
- 使用指定的初始值设定项聚合匿名结构初始化
- 不同的类或结构初始化方法之间的性能差异是什么?
- 如何在结构初始化中获取成员C++
- C++正确的结构初始化
- 使用大括号进行结构初始化
- 内部结构初始化不起作用 - C++
- 使用嵌套结构初始化并集
- 使用匿名结构初始化联合
- 结构初始化语法
- 结构初始化的 C++ 向量
- C++嵌套结构初始化和访问成员
- 结构初始化中的常量正确性
- 使用 C++ 中的自定义元素进行 Const 结构初始化
- 如何在结构C++初始化内置数组
- Visual C++ 模板类成员结构初始化语法糖
- C++结构初始化
- C 在结构初始化过程中带有内部阵列的奇怪错误
- 此C/C 的结构初始化器如何使用足够的字段工作