我昨天遇到了一个错误,虽然它很容易解决,但我想确保我正确理解C++.
我有一个受保护成员的基类:
class Base
{
protected:
int b;
public:
void DoSomething(const Base& that)
{
b+=that.b;
}
};
Run Code Online (Sandbox Code Playgroud)
这编译并且工作得很好.现在我扩展Base但仍想使用b:
class Derived : public Base
{
protected:
int d;
public:
void DoSomething(const Base& that)
{
b+=that.b;
d=0;
}
};
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下DoSomething
仍然参考a Base
,而不是Derived
.我希望我仍然可以访问that.b
内部Derived
,但我得到一个cannot access protected member
错误(MSVC 8.0 - 还没有尝试过gcc).
显然,添加一个公共getter b
解决了这个问题,但我想知道为什么我无法直接访问b
.我认为,当您使用公共继承时,受保护的变量对派生类仍然可见.
C++类的私有成员被设计为对其他类实例不可见.我很困惑,因为可以访问私人成员,如下所示!有谁可以向我解释一下?
这是我的代码:
#include <iostream>
using namespace std;
class Person
{
private:
char* name;
int age;
public:
Person(char* nameTemp, int ageTemp)
{
name = new char[strlen(nameTemp) + 1];
strcpy(name, nameTemp);
age = ageTemp;
}
~Person()
{
if(name != NULL)
delete[] name;
name = NULL;
}
bool Compare(Person& p)
{
//p can access the private param: p
//this is where confused me
if(this->age < p.age) return false;
return true;
}
};
int main()
{
Person p("Hello, world!", 23); …
Run Code Online (Sandbox Code Playgroud) 这个例子很容易解释我的问题:
class Vector3
{
float _x;
float _y;
float _z;
public :
/// constructors and stuff
};
class Point : public Vector3
{
// some BS
Point(float _x):Vector3(float _x)
{}
};
main()
{
Point aPoint(3);
Point anotherPoint(4);
// WHY DOES THIS WORK and copy _x,_y & _z properly
aPoint = anotherPoint;
}
Run Code Online (Sandbox Code Playgroud)
基本上,我无法理解为什么=
派生类可以复制_x
,_y
并且_z
,即使它不应该访问它们,因为它们是私有的.