![](/img/trans.png)
[英]C++ lambda conversion — why is candidate constructor not viable: no known conversion from lambda to std::function
[英]C++ Candidate constructor not viable: no known conversion
這是一個PNG類,在類文檔中列出了以下兩個構造函數。
PNG::PNG ( string const & file_name )
Creates a PNG image by reading a file in from disk.
Parameters
file_name Name of the file to be read in to the image.
PNG::PNG ( size_t width, size_t height )
Creates a default PNG image of the desired dimensions (that is, a width x height opaque white image).
Parameters
width Width of the new image.
height Height of the new image.
我使用以下代碼來調用構造函數:
int main(){
PNG in_image=new PNG("in.png");
size_t width=in_image.width();
size_t height=in_image.height();
PNG out_image=new PNG(width,height);
}
但是出現以下錯誤:
main.cpp:5:6: error: no viable conversion from 'PNG *' to 'PNG'
PNG in_image=new PNG("in.png");
^ ~~~~~~~~~~~~~~~~~
./png.h:62:9: note: candidate constructor not viable: no known conversion from
'PNG *' to 'const PNG &' for 1st argument; dereference the argument with *
PNG(PNG const & other);
^
./png.h:55:9: note: candidate constructor not viable: no known conversion from
'PNG *' to 'const string &' (aka 'const basic_string<char,
char_traits<char>, allocator<char> > &') for 1st argument
PNG(string const & file_name);
^
main.cpp:8:6: error: no viable conversion from 'PNG *' to 'PNG'
PNG out_image=new PNG(width,height);
^ ~~~~~~~~~~~~~~~~~~~~~
./png.h:62:9: note: candidate constructor not viable: no known conversion from
'PNG *' to 'const PNG &' for 1st argument; dereference the argument with *
PNG(PNG const & other);
^
./png.h:55:9: note: candidate constructor not viable: no known conversion from
'PNG *' to 'const string &' (aka 'const basic_string<char,
char_traits<char>, allocator<char> > &') for 1st argument
PNG(string const & file_name);
誰能給我一些暗示,說明我的構造函數調用有什么問題嗎? 謝謝
您應該這樣寫:
PNG *in_image=new PNG("in.png");
size_t width=in_image->width();
size_t height=in_image->height();
PNG *out_image=new PNG(width,height);
使用new應該為您提供PNG*
即指向對象的指針。
您應該這樣寫:
PNG in_image("in.png");
size_t width = in_image.width();
size_t height = in_image.height();
PNG out_image(width, height);
C ++不是Java-您可以使用new
來動態分配對象,但如果不這樣做,則不要使用它。 除非確實需要,否則不應該使用new
。
運營商新的類型X
將分配內存為X
,並返回它的地址是型X*
。
因此,您應該將其收集到一個指針變量中:
PNG* in_image = new PNG("in.png"); // in_image points to the newly created PNG object
size_t width = in_image.width();
size_t height = in_image.height();
PNG* out_image = new PNG(width,height); // another object is created and out_image points to it
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.