我有以下兩個檔案
foob??ar.h
#ifndef FOOBAR_H
#define FOOBAR_H
#include <cstring>
class Foo {
public:
int x;
Foo(int x);
};
class Bar {
public:
char* name;
Foo foo;
Bar(Foo foo);
};
#endif // FOOBAR_H
和 foobar.cpp
#include "foobar.h"
Foo::Foo(int x) {
// Do something
}
Bar::Bar(Foo foo) {
// Do something
}
嘗試編譯這些會g -c foobar.cpp -o foobar.o導致以下錯誤:
foobar.cpp: In constructor ‘Bar::Bar(Foo)’:
foobar.cpp:9:17: error: no matching function for call to ‘Foo::Foo()’
Bar::Bar(Foo foo) {
^
foobar.cpp:5:1: note: candidate: ‘Foo::Foo(int)’
Foo::Foo(int x) {
^~~
foobar.cpp:5:1: note: candidate expects 1 argument, 0 provided
In file included from foobar.cpp:1:
foobar.h:5:7: note: candidate: ‘constexpr Foo::Foo(const Foo&)’
class Foo {
^~~
foobar.h:5:7: note: candidate expects 1 argument, 0 provided
foobar.h:5:7: note: candidate: ‘constexpr Foo::Foo(Foo&&)’
foobar.h:5:7: note: candidate expects 1 argument, 0 provided
據我了解 g 的輸出是它要求我有一個默認的 foo 建構式。為什么?我希望將 foo 物件傳遞給 bar 的建構式,為什么它需要在任何地方呼叫默認建構式?無論如何,我不想擁有無引數建構式,因為我需要 x 具有特定的用戶定義值。
uj5u.com熱心網友回復:
您正在嘗試在Foo此處默認構造一個:
Bar::Bar(Foo foo) {
// the member variable `foo` would have been default constructed here
// Do something
}
但Foo沒有默認建構式。一種可能的解決方案是在成員初始值設定項串列中對其進行初始化:
Bar::Bar(Foo foo) : foo(std::move(foo)) { // now uses the move constructor instead
// Do something
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/337808.html
標籤:C
上一篇:使用std::chrono::from_stream()決議時間格式“DD/MM/YYYYathh:mm:ss”和其他格式
