C++ 错误:构造函数在此上下文中受保护 #包括 使用名称空间std; 阶级基础{ 私人: INTA; 受保护的: Base(){}; 虚~Base(){}; }; 派生类:私有基{ 私人: int b; 公众: 派生(){}; ~Derived(){}; 无效测试(){ 基地世界; }; }; int main(){ }
inherit.cc | 7 col 3|错误:“Base::Base()”受保护C++ 错误:构造函数在此上下文中受保护 #包括 使用名称空间std; 阶级基础{ 私人: INTA; 受保护的: Base(){}; 虚~Base(){}; }; 派生类:私有基{ 私人: int b; 公众: 派生(){}; ~Derived(){}; 无效测试(){ 基地世界; }; }; int main(){ },c++,C++,inherit.cc | 7 col 3|错误:“Base::Base()”受保护 inherit.cc | 17 col 9 |错误:在此上下文中 inherit.cc | 8 col 11 |错误:“virtual Base::~Base()”受保护 inherit.cc | 17 col 9 |错误:在此上下文中 但是为什么呢 为什么这是正确的 #include<iostream> using namespace std; class Base{ private:
inherit.cc | 17 col 9 |错误:在此上下文中
inherit.cc | 8 col 11 |错误:“virtual Base::~Base()”受保护
inherit.cc | 17 col 9 |错误:在此上下文中
但是为什么呢 为什么这是正确的
#include<iostream>
using namespace std;
class Base{
private:
int a;
protected:
Base(){};
virtual ~Base(){};
};
class Derived:private Base{
private:
int b;
public:
Derived(){};
~Derived(){};
void test(){
Base world;
};
};
int main(){
}
#包括
使用名称空间std;
阶级基础{
私人:
INTA;
受保护的:
Base(){};
虚~Base(){};
void test2(){};
};
派生类:私有基{
私人:
int b;
公众:
派生(){};
~Derived(){};
无效测试(){
test2();
};
};
int main(){
}
在第一个示例中,您在派生的类的test()方法中创建了Base
的对象
在第二个示例中,您访问方法test2()
,该方法在Base
&Derived
中受保护
请注意类的访问说明符的规则:
Protected
访问说明符意味着声明为Protected
的成员可以从类外部访问,但只能在从类派生的类中访问
在私有
继承的情况下:
基类的所有公共成员都成为派生类的私有成员&
基类的所有受保护成员都成为派生类的私有成员
在示例1中,
尽管,派生的
派生自基
,但它只能对派生的
对象的基
的受保护成员进行访问,该对象的成员函数(test()
)不是被调用的任何其他基
类对象。
假设您无法创建Base
对象
在示例2中,
对其成员函数(test()
)正在被调用的对象调用test2()
,如上所述,Derived
类可以访问其成员函数正在被调用的Derived
对象的Base
的受保护的成员,因此test2()
可以调用
读得好:
在void-Derived::test()
中,您尝试创建基类的实例。因为没有关于参数的任何说明-它尝试调用基本默认构造函数,但它受保护
-而不是公共
在Derived::test()
的末尾也将被称为析构函数,但它也受到保护。因此,您不能为构造函数和析构函数创建带有此类修饰符的Base
类的实例
#include<iostream>
using namespace std;
class Base{
private:
int a;
protected:
Base(){};
virtual ~Base(){};
void test2(){};
};
class Derived:private Base{
private:
int b;
public:
Derived(){};
~Derived(){};
void test(){
test2();
};
};
int main(){
}
使用名称空间std;
阶级基础{
私人:
INTA;
受保护的:
Base(){}
基(inta):a(a){}
虚拟~Base(){}
void test2(){}
};
派生类:私有基{
私人:
int b;
派生(intb):基(b){};
公众:
派生():Base(){};//使用受保护的构造函数
~Derived(){};
基本*测试(){
新派生(-1);//使用其他受保护的构造函数
};
};
可能重复@tinybit:请仔细阅读说明,尽管派生自Base,但它只能访问其成员函数(test())的派生对象的Base的受保护的Base成员正在调用的不是任何其他基类对象。能否添加一些纯文本以明确代码的含义并构造您的答案?
#include<iostream>
using namespace std;
class Base{
private:
int a;
protected:
Base(){}
Base(int a) : a(a) {}
virtual ~Base(){}
void test2(){}
};
class Derived:private Base{
private:
int b;
Derived(int b) : Base(b) {};
public:
Derived() : Base() {}; // uses protected constructor
~Derived(){};
Base* test(){
new Derived(-1); // uses the other protected constructor
};
};