gpt4 book ai didi

c++ - 错误 C2248 : Protected Default Constructor C++ within an class owned by another class

转载 作者:行者123 更新时间:2023-11-30 03:05:14 26 4
gpt4 key购买 nike

我正在尝试解决我从 Microsoft Visual Studio 10 编译器收到的这个错误。错误是:某些类:错误 C2248:无法访问类“”中声明的 protected 成员。这是重现此错误的代码。我似乎无法弄清楚如何创建一个对象,该对象拥有另一个具有 protected 默认构造函数的对象。我有另一个构造函数,它接受一个输入参数,但无论我应用什么逻辑推理,似乎都无法调用它。显然,我遗漏了一些愚蠢的或非常重要的东西,所以我把它放在这里看看是否有人能发现我的错误。感谢大家!!!

#ifndef FOO_H
#define FOO_H

class Foo {
public :
int myFooInt;

~Foo();

Foo(int fooInt);

protected : //Uncomment to generate C2248 Error
Foo();
};

#endif

.

#include "foo.h"

Foo::Foo() {

}
Foo::Foo(int fooInt) : myFooInt(fooInt) {

}

Foo::~Foo() {
}

.

#ifndef GOO_H
#define GOO_H

#include "foo.h"

class Goo {
public :

~Goo();

Goo();

Goo(Foo foo);

Foo myFoo;

};

#endif

.

#include "Goo.h"

Goo::Goo() {

}

Goo::Goo(Foo foo) : myFoo (foo) {
}

Goo::~Goo() {
}

.

#include "foo.h"
#include "goo.h"

void main() {
Foo foo(5);
Goo goo(foo);
}

最佳答案

I have another constructor that takes an input parameter but can't seem to call it no matter what logical reasoning I apply.

啊,现在我们到了重要的部分(很抱歉,其他答案似乎没有让您相信理解 protected 关键字,但您理解您提出问题的方式似乎有点困惑)。您确实有那个构造函数,但您有一个默认构造函数。你写了多少工作构造函数并不重要;不工作的仍然会导致编译时错误。

容器类的默认构造函数没有初始化列表,因此将尝试使用数据成员的默认构造函数。由于您无权访问成员的默认构造函数,因此编译容器的默认构造函数失败。

可能的解决方案:在容器的默认构造函数的初始化列表中使用另一个构造函数显式初始化成员。这意味着您必须以某种方式弥补值(value)。 (这并不总是可能的。当这种情况发生时,这是编译器告诉您默认构造函数对容器类没有意义的方式。:))

关于c++ - 错误 C2248 : Protected Default Constructor C++ within an class owned by another class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7906083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com