[英]How to use a member variable in a base class function when its size is only known to the derived class
I want to implement a function in a baseclass that uses members of its derived classes. 我想在使用其派生类成员的基类中实现一个功能。 So with each DerivedClass, I would have a member of a different value.
因此,对于每个DerivedClass,我将拥有一个具有不同值的成员。 Here's an example.
这是一个例子。 The
BaseClass
has member function Foo()
which uses variable arrStr
. BaseClass
具有成员函数Foo()
,该函数使用变量arrStr
。 This content of this NUL terminated char array however is only to be found in a derived class. 但是,此NUL终止的char数组的此内容只能在派生类中找到。 How can I make
BaseClass
"know" the variable arrStr
without knowing its size? 如何在不知道变量
arrStr
情况下使BaseClass
“知道”变量arrStr
? Is that even possible? 那有可能吗?
class BaseClass
{
public:
BaseClass();
~BaseClass();
protected:
void Foo()
{
prtinf("%s\n", arrStr);
};
};
class DerivedClass : public BaseClass
{
public:
DerivedClass();
~DerivedClass();
protected:
char arrStr[] = "FooString!";
};
Add (pure) virtual access functions in your base class which you implement in the derived class. 在派生类中实现的基类中添加(纯)虚拟访问函数。
#include <iostream>
#include <string>
class BaseClass
{
protected:
void Foo()
{
std::cout << GetString() << std::endl;
}
private:
virtual std::string GetString() const = 0;
};
class DerivedClass : public BaseClass
{
private:
virtual std::string GetString() const override
{
return "FooString!";
}
};
How can I make BaseClass "know" the variable arrStr without knowing its size?
如何在不知道变量大小的情况下使BaseClass“知道”变量arrStr? Is that even possible?
那有可能吗?
You insert it as a parameter when calling Foo: 您在调用Foo时将其作为参数插入:
class BaseClass
{
public:
virtual void Process() = 0;
protected:
void Foo(char* str) // <-- value inserted here as parameter
{
prtinf("%s\n", arrStr);
}
};
class DerivedClass : public BaseClass
{
public:
void Process() override
{
Foo(arrStr); // call in derived class, with derived value
}
protected:
char arrStr[] = "FooString!";
};
Client code: 客户代码:
BaseClass * b = new DerivedClass;
b->Process(); // call Foo(arrStr) internally
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.