C++ 如何创建创建派生 class 对象的基 class,并访问基 class 的私有成员?
C++ How to create base class which creates derived class object, and access private members of base class?
有什么方法可以让 derived class
访问 base class
的 private
成员,同时能够创建 derived
base class
中的 base class
方法上的对象?
像这样:
class Derived;
class Base
{
public:
void func()
{
// I want to create the derived obj here
Derived derived;
derived.func();
}
public:
int mBase = 5;
};
class Derived : public Base
{
public:
void func()
{
// I need to have access to the private members of Base inside this method
mBase = 6;
}
};
错误如下:
Error: derived uses undefined class Derived.
我怎样才能做这样的事情?
谢谢
为了能够使用 Derived
class 并调用其中的成员函数(包括构造函数和析构函数) full 定义需要能得到的。在这种情况下,它不在 Base::func
函数中。
解决方法很简单:不要内联定义func
,声明它然后在定义Derived
class之后实现(定义)它。
a derived class that access the private members of the base class
通常只写protected
而不是private
。你有什么理由不能这样做吗?
Error: derived uses undefined class Derived.
只需在基础 class 定义中 声明 func
,并且仅在派生 define 之后 class 已定义:
class Base {
public:
void func();
protected:
int mBase = 5;
};
class Derived : public Base {
public:
void func() {
mBase = 6;
}
};
void Base::func() {
Derived derived;
derived.func();
}
您应该阅读 多态性。你可能想要的是使 func() virtual:
class Base
{
public:
virtual void func() { /* Base behavior */ } // or pure = 0
virtual ~Base() = default; // don't forget!
public:
int mBase = 5;
};
class Derived : public Base
{
public:
void func() override
{
// Derived behavior
}
};
关于访问Base::mBase
,您有两个选择:
- 使
mBase
受保护
- 添加一个受保护的 setter,您在 Derived 中使用它来修改它。
有什么方法可以让 derived class
访问 base class
的 private
成员,同时能够创建 derived
base class
中的 base class
方法上的对象?
像这样:
class Derived;
class Base
{
public:
void func()
{
// I want to create the derived obj here
Derived derived;
derived.func();
}
public:
int mBase = 5;
};
class Derived : public Base
{
public:
void func()
{
// I need to have access to the private members of Base inside this method
mBase = 6;
}
};
错误如下:
Error: derived uses undefined class Derived.
我怎样才能做这样的事情?
谢谢
为了能够使用 Derived
class 并调用其中的成员函数(包括构造函数和析构函数) full 定义需要能得到的。在这种情况下,它不在 Base::func
函数中。
解决方法很简单:不要内联定义func
,声明它然后在定义Derived
class之后实现(定义)它。
a derived class that access the private members of the base class
通常只写protected
而不是private
。你有什么理由不能这样做吗?
Error: derived uses undefined class Derived.
只需在基础 class 定义中 声明 func
,并且仅在派生 define 之后 class 已定义:
class Base {
public:
void func();
protected:
int mBase = 5;
};
class Derived : public Base {
public:
void func() {
mBase = 6;
}
};
void Base::func() {
Derived derived;
derived.func();
}
您应该阅读 多态性。你可能想要的是使 func() virtual:
class Base
{
public:
virtual void func() { /* Base behavior */ } // or pure = 0
virtual ~Base() = default; // don't forget!
public:
int mBase = 5;
};
class Derived : public Base
{
public:
void func() override
{
// Derived behavior
}
};
关于访问Base::mBase
,您有两个选择:
- 使
mBase
受保护 - 添加一个受保护的 setter,您在 Derived 中使用它来修改它。