【发布时间】:2015-08-08 16:28:25
【问题描述】:
我正在重新编写一些 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;
}
谢谢!
【问题讨论】:
-
另一个副本,可能有更有用的答案:stackoverflow.com/questions/2685172/…
-
@juanchopanza stackoverflow.com/questions/926752/… 可能是一个更好的副本,它显示了他的确切情况
-
@juanchopanza 的回答并没有真正解决我的问题。
-
@dwcanillas 的回答很有帮助,让我前进,但我仍然感到困惑。我更新了问题以反映我的困惑。
-
in STR_2 name=name 我认为应该是 name =n
标签: c++ struct constructor g++