简体   繁体   English

c ++继承,构造函数真正的调用者

[英]c++ inheritance, constructor real caller

I have class A: 我有A班:

class A
{
    A(const String& name)
    {
        doSomething1();
    }
}

and I have also class B 我也有B班

class B : A
{
    B(const String& name): A(name)
    {
        doSomething2();
    }
}

So if I call B() it will call also A() and it will result with 2x calls doSomething(). 因此,如果我调用B(),它也将调用A(),它将导致2x调用doSomething()。 Is there any way how to discover in A`s constructor that it is called directly like: A() and when indirectly: B() ? 有没有办法如何在A`s构造函数中发现它被直接调用:A()和间接调用:B()?

Thanks 谢谢

EDIT: Well ok, it is not the same method doSomething() it is more like doSomething1() and doSomething2() but I want call the most outside function so if A has doSomething1() and B doSomething2(), after call B() I want to execute just doSomething2() 编辑:好吧,它不是相同的方法doSomething()它更像是doSomething1()和doSomething2()但我想调用最多的外部函数,所以如果A有doSomething1()和B doSomething2(),在调用B之后( )我想执行doSomething2()

In general there's no way to discover from a base class if the object you're referring to is of a derived type. 通常,如果您引用的对象是派生类型,则无法从基类中发现。

Anyway your design is most likely flawed, something like this could also work: 无论如何,你的设计很有可能存在缺陷,这样的事情也可以起作用:

#include <iostream>
#include <string>
using namespace std;

class A
{
public:
    A(const string& name)
    {
        doSomethingFromA();
    }

    void doSomethingFromA() {
        cout << "called from A" << endl;
    };
protected:
   A(const string& name, bool fromB)
   {
       doSomethingFromB();
   }

   void doSomethingFromB() {
        cout << "called from B" << endl;
    };
};

class B : public A
{
    public:
    B(const string& name): A(name, true)
    {
    }

};


int main() {

    A obj1("str");

    B obj2("str");

    return 0;
}

http://ideone.com/jj8Df1 http://ideone.com/jj8Df1

by exploiting the visibility of constructors you might pass additional info to the base class. 通过利用构造函数的可见性,您可以将其他信息传递给基类。 Otherwise I'd advice using a slightly modified CRTP that renders your base class aware of the object itself (they become an entire different entity). 否则,我建议使用稍微修改过的CRTP ,使您的基类知道对象本身(它们成为一个完全不同的实体)。

You could have two overloads of doSomething as follow but... 你可以有两个doSomething重载如下,但......

void doSomething(A*);
void doSomething(B*);

And on the call site you do: 在通话网站上,您可以:

doSomething(this);

( this is either A* or B* so it will call the appropriate function.) thisA*B*所以它会调用相应的函数。)

class A
{
    A(const String& name)
    {
        doSomething(this);
    }
}

class B : A
{
    B(const String& name): A(name)
    {
        doSomething(this);
    }
}

But , as other said in the comment, you have a design issue! 但是 ,正如其他人在评论中所说,你有一个设计问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM