为什么我无法实例化类中的对象?

问题描述 投票:0回答:1

我有这三个代码:

#pragma once

class Rect
{
private:
    int m_Thing;
public:
    Rect(int thing)
    {
        m_Thing = thing;
    }

    void create(int thing)
    {
        m_Thing = thing;
    }
};
#pragma once
#include "Rect.h"

class Brick
{
private:
    Rect floatRect;
public:
    Brick()
    {
        floatRect.create(28);
    }
};
#include "mre.h"
#include <iostream>

int main()
{
    Brick brick;
}

由于某种原因,我收到一个错误,提示我需要一个默认构造函数。我做了一个,然后在 Rect 对象上出现了未解决的外部符号错误。这就是我被困住的地方。我怎样才能实例化它?

c++ linker-errors sfml
1个回答
0
投票

当您调用类的默认构造函数时,除非以其他方式指定,否则它的所有成员都是默认构造的。如果我们想明确地写出在

Brick()
的调用中发生的事情,它看起来像这样。

Brick() : floatRect()
{
    floatRect.create(28);
}

在这里我们可以看到,在 成员初始值设定项列表 中,它尝试调用

Rect
的默认构造函数,该构造函数被隐式删除,因为您有一个用户定义的构造函数。如果您想创建
Rect
,您可以执行以下操作。

Brick() : floatRect(28)
{
    
}

成员初始化字段专门用于初始化或将参数传递给成员的构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.