我回過頭來寫一些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;
}
謝謝!
另一個重複,可能與更有用的答案:http://stackoverflow.com/questions/2685172/g-no-matching-function-call-error – juanchopanza
@juanchopanza http://stackoverflow.com/questions/926752/爲什麼要我更喜歡使用成員初始化列表可能是一個更好的重複,它顯示了他的確切情況 – dwcanillas
@ juanchopanza的答案並沒有真正解決我的問題。 – darkpbj