簡體   English   中英

從構造函數初始化結構

[英]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_1 myStr1;為什么STR_1 myStr1; STR_2需要調用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;

然而,僅出於充分的理由,我才選擇第一種選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM