【问题标题】:C++ no instance of constructor matches the argument list e0289C++没有构造函数实例匹配参数列表e0289
【发布时间】:2021-12-10 06:34:12
【问题描述】:

所以代码应该可以工作,但事实并非如此。我该如何解决? enter image description here

    #include <iostream>

class Button{
private:
    unsigned width; 
    unsigned height;

public:

    Button(): width(0), height(0){};

    Button(unsigned _width, unsigned _height): 
        width(_width), height(_height){};

    unsigned getWidth(){ return width; };

    unsigned getHeight(){ return height; };

    void setWidth(unsigned _width){ width = _width; };

    void setHeight(unsigned _height){ height = _height; }; 

};

class Window{
protected:
    Button button;

    int x;
    int y;

public:

    Window(){
        x = y = 0;
    }

    Window(int _x, int _y, Button _button):
        x(_x), y(_y), button(_button){};
    
    ~Window(){
        x = 0;
        y = 0;
    }

};

class Menu: public Window{
private:
    char *title;

public:
    Menu() = default;

    Menu(char* _title, int _x, int _y, Button _button):
        title(_title), Window(_x, _y, _button){
            std::cout << "Menu has been created." << std::endl;
        };
    
    ~Menu(){
        title = NULL;
        std::cout << "Menu has been deleted." << std::endl;
    }

    friend std::ostream& operator<<(std::ostream& os, Menu& menu){
        os << "Button \"" << menu.title << "\" on (" << menu.x << "," << menu.y << ") with size " << menu.button.getWidth() << "x" << menu.button.getHeight() << ".";
        return os;  
    } 
    
};


int main(){

    Button button(10, 10);

    Menu menu("A main menu", 5, 5, button);

    std::cout << menu << std::endl;

    return 0;

}

【问题讨论】:

  • 您不能在 C++ 中将字符串文字作为 char* 传递,因为字符串文字是不可变的。你需要有 const char* 标题。
  • 这并没有解决问题,但Window 的析构函数中的x = 0; y = 0; 毫无意义。该对象正在消失,在析构函数完成后,您无法访问xyWindow 中没有需要显式销毁的东西,所以不要写析构函数;默认析构函数可以正常工作。

标签: c++ class constructor declaration string-literals


【解决方案1】:

至少声明数据成员titlelike

const char *title;

和类似的构造函数

Menu( const char* _title, int _x, int _y, Button _button):
    Window(_x, _y, _button), title(_title) {
        std::cout << "Menu has been created." << std::endl;
    };

因为 C++ 中的字符串文字(与 C 相对)具有常量字符数组的类型。

虽然数据成员title 的类型const char * 使用std::string 类型会好得多

std::string title.

【讨论】:

  • @4iel 完全没有。不客气。:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 2014-09-09
  • 1970-01-01
  • 2021-07-02
  • 2013-10-29
  • 1970-01-01
相关资源
最近更新 更多