如何在使用组合时使用默认构造函数?在 visual studio

How to use default constructor while using composition? in visual studio

当我在 main 中声明 Game 对象时,我不断收到:// C2512:没有合适的默认构造函数可用,我正在使用 visual studio,在其他编译器上,该错误并不总是出现。

我试图改变定义和初始化的方式,但它一直给我同样的错误,像这样的问题在考试中有一个问题是有默认的参数化构造函数,其中一个参数是另一个 class 组合中的对象,但我在代码中这样做它给了我上面的错误

那么如何在使用组合时使用默认构造函数???

#include <iostream>
#include <string>
//#include "Game.h"
//#include "Screen.h"
using namespace std;


class Screen
{
private:
    int resolution;
    int brightness;
    string color;
public:
    Screen(int br = 20, int rl = 10, string colr = "green");
};

Screen::Screen(int br, int rl, string colr) :resolution(rl), brightness(br), color(colr)  {}



class Game {
protected:
    string name;
    Screen screen1;
public:
    Game(Screen& ok, string nam = "minecraft");
};


Game::Game(Screen& ok, string nam) : screen1(ok), name(nam)
{ }



int main()
{
    //Screen screen1;
    Game gg;




    return 0;
}

//screen1 = ok;


构造器 Game(Screen& ok, string nam = "minecraft"); 需要获取对 Screen 对象的引用。

并且当您像这样创建 Game 对象时: Game gg;

没有对 Screen 对象的引用。

constactur 调用的一个很好的例子是:

Screen s;
Game gg(s);

其他提示是将实现放在其他文件或声明它的地方。 所以

Screen::Screen(int br, int rl, string colr) :resolution(rl), brightness(br), color(colr) {}

Screen(int br = 20, int rl = 10, string colr = "green"); 将是:

Screen(int br = 20, int rl = 10, string colr = "green") 
    :resolution(rl), brightness(br), color(colr)  {}
    Game(string nam = "minecraft") : screen1(Screen()), name(nam) {}

screen1(Screen()) 使用默认参数创建一个 Screen 对象并分配给 screen1。

整个程序:

#include <iostream>
#include <string>
//#include "Game.h"
//#include "Screen.h"
using namespace std;


class Screen
{
private:
    int resolution;
    int brightness;
    string color;
public:
    Screen(int br = 20, int rl = 10, string colr = "green"):resolution(rl), brightness(br), color(colr)  {}
};


class Game {

public:
    Game(string nam = "minecraft") : screen1(Screen()), name(nam) {}

protected:

    Screen screen1;
    string name;
};


int main()
{
    //Screen screen1;
    Game gg;

    return 0;
}