相关疑难解决方法(0)

访问派生类中的受保护成员

我昨天遇到了一个错误,虽然它很容易解决,但我想确保我正确理解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++

56
推荐指数
3
解决办法
6万
查看次数

可以从同一类型的另一个对象访问私有变量吗?

可能重复:
使用私有修饰符,为什么可以直接访问其他对象中的成员?

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)

c++ visual-c++ c++11

12
推荐指数
2
解决办法
2万
查看次数

默认赋值运算符可以访问基类的私有成员

这个例子很容易解释我的问题:

http://pastebin.com/VDBE3miY

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,即使它不应该访问它们,因为它们是私有的.

c++

2
推荐指数
1
解决办法
2286
查看次数

标签 统计

c++ ×3

c++11 ×1

visual-c++ ×1