C++窗口类: 解决'Size' 类缺少默认构造函数的错误
#include
class Size { public: int width, height; Size(const int& width, const int& height) : width(width), height(height) {
}
};
class Window { private: std::string title; Size windowSize;
public:
// Constructor that sets the window size
Window(const Size& size)
: windowSize(size) {
SetWindowSize(size);
}
// Constructor that sets the window title
Window(const std::string& title)
: title(title), windowSize(Size(0, 0)) {
SetWindowTitle(title);
}
// Constructor that sets both the window title and size
Window(const std::string& title, const Size& size)
: title(title), windowSize(size) {
SetWindowTitle(title);
SetWindowSize(size);
}
// Method to set the window title
void SetWindowTitle(const std::string& newTitle) {
title = newTitle;
std::string command = "title " + title;
system(command.c_str());
}
// Method to get the window title
std::string GetWindowTitle() const {
return title;
}
// Method to set the window size
void SetWindowSize(const Size& newSize) {
windowSize = newSize;
std::string command = "mode con cols=" + std::to_string(windowSize.width) + " lines=" + std::to_string(windowSize.height);
system(command.c_str());
}
// Method to get the window size
Size GetWindowSize() const {
return windowSize;
}
};
请问29行的: Window(const std::string& title) : title(title) { SetWindowTitle(title); } 会报错 类 'Size' 不存在默认构造函数
内容:
这个错误是因为在Window类的构造函数中,Size对象windowSize需要进行初始化,而Size类并没有默认构造函数。解决这个问题的方法是在Window构造函数的初始化列表中,调用Size类的构造函数来初始化windowSize对象。例如,可以将29行的构造函数修改如下:
Window(const std::string& title)
: title(title), windowSize(Size(0, 0)) {
SetWindowTitle(title);
}
这样就会使用Size类的构造函数来初始化windowSize对象。需要根据实际需求来确定Size类的构造函数的参数值。
原文地址: https://www.cveoy.top/t/topic/qd4B 著作权归作者所有。请勿转载和采集!