簡體   English   中英

C ++編譯器錯誤:“初始化時無法將std :: list(*)()轉換為std :: list *”

[英]C++ compiler error: “Cannot convert std::list (*)() to std::list* in initialization”

假設以下代碼:

std::list<Test1> l1();
std::list<Test1> *pl1 = &l1;

編譯器給出錯誤(略過一點):在初始化時Cannot convert std::list (*)() to std::list*

如果在沒有括號的情況下初始化l1,一切都很好。 這里有什么問題,我該如何避免?

如您所寫, l1是一個函數聲明,不帶參數,返回std::list<Test1> 想象一下,如果名稱不同,這可能更容易吞下。

std::list<Test1> make_tests(); // cleary a function declaration, no?
std::list<Test1> l1(); // also a function declaration
std::list<Test1> l1; // can't be a function declaration, no ()
std::list<Test1> l1{}; // also can't be a function declaration

要發表您的評論:

std::list<Test1> l1 = std::list<Test1>();

解決您的問題,因為只有一種方法可以解釋它,即將變量聲明后跟賦值。


這往往很難吞咽,因此讓我將它放在一個更大的程序中:

std::list<Test1> make_tests(); // according to your rules, should be a variable

int main() {
    std::list<Test1> tests = make_tests();
}

std::list<Test1> make_tests() {
    // ... function body ...
}

另外,如果您使用的是C++11或更高版本,則可以使用{}

std::list<Test1> l1{};

暫無
暫無

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

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