在C ++上初始化类对象

时间:2014-07-08 01:55:30

标签: c++ oop

我对如何在超类上没有默认构造函数的情况下进行对象初始化存在疑问。

#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的构造函数中初始化m_pA类型的A对象,VC正在抛弃我:

"m_pA" is not a nonstatic data member or base class of class "B"

您可以看到已编译的示例和错误 here

我想知道为什么以及如何在没有默认构造函数的情况下初始化类的成员对象,以及为什么我错了。

提前致谢!

3 个答案:

答案 0 :(得分:1)

构造子类时需要显式初始化基类。

B(std::string title, int xpos, int ypos)
    : A(title, xpos, ypos)
{}

您可能也应该通过const引用传递这些字符串,否则您将制作一堆不必要的副本。

答案 1 :(得分:1)

您的代码有一些错误。首先,对于继承的类来访问受保护的变量/函数,必须为继承的类提供支持。其次,您的私有变量m_pA是一个指针。你不能像A的实例一样初始化指向A的指针。看看这段代码:

#include <iostream>

class A
{
    friend class B;
protected:  
    A();
    A(std::string title, int xpos, int ypos);
};

A::A()
{
//Do something
}
A::A(std::string title, int xpos, int ypos)
{
//Do something
}

class B : A
{
protected:
    A* m_pA;    
public:
    B(std::string title, int xpos, int ypos);
};

B::B(std::string title, int xpos, int ypos)
{
    m_pA = new A(title, xpos, ypos);
}

int main() {

    return 0;
}

您可以在此处验证:http://ideone.com/gL1OxH

答案 2 :(得分:0)

class B : A
{
protected:
    A* p;
    A a;
public:
    B(std::string title, int xpos, int ypos)
         : A(title, xpos, ypos)          // init base
         , p(new A(title, xpos, ypos))   // init pointer
         , a(title, xpos, ypos)          // init member
    {}
};