【发布时间】:2023-03-17 14:50:01
【问题描述】:
我对如何在超类上没有默认构造函数的情况下进行对象初始化有疑问。
#include <iostream>
class A
{
protected:
A(std::string title, int xpos, int ypos);
};
class B : A
{
protected:
//Is that correct?
A* m_pA(std::string title, int xpos, int ypos);
//Why not just A* m_pA;?
public:
B(std::string title, int xpos, int ypos);
};
B::B(std::string title, int xpos, int ypos) : m_pA(title, xpos, ypos)
{
//does nothing yet.
}
如你所见,我试图在 B 的构造函数中初始化 A 类型的 m_pA 对象,VC 正在抛出我:
"m_pA" is not a nonstatic data member or base class of class "B"
您可以看到编译的示例和错误here。
我想知道为什么以及如何在没有默认构造函数的情况下初始化一个类的成员对象,以及为什么我错了。
提前致谢!
【问题讨论】:
-
你真的是要从A继承,并且有一个指向A的成员指针吗?无论如何,受保护的声明是一种方法。你仍然需要初始化基础
-
A* m_pA(std::string title, int xpos, int ypos);是 B 类中的一个函数,返回指向 A 的指针。 -
是的@sp2danny 你可能是对的,我的脑袋,只是太困惑了。 D:无论如何,如果我想要一个 A 类型的对象,我该如何初始化它?我只想调用 B 并且 A 将被初始化,这就是目标,问题可能不清楚......而 drescherjm 你是对的!
-
因为,正如已经说过的
m_pA不是非静态成员对象,试图在 ctor 初始化列表中对其进行初始化是错误的。无论如何,您想将参数传递给那里的A基类子对象....(将列表中的m_pA替换为A) -
彻底摆脱 m_pA。将构造函数更改为
B::B(std::string title, int xpos, int ypos) : A(title, xpos, ypos) {}