gpt4 book ai didi

c++ protected 指向同一类的指针成员和访问权限

转载 作者:太空狗 更新时间:2023-10-29 20:48:32 26 4
gpt4 key购买 nike

示例代码包含在消息的底部。我对类中的 protected 访问说明符感到困惑。我已经定义了一个类节点,它有一个 protected 字符串成员名称

字符串名称;

和一个节点指针 vector

vector 参数;

之前我以为node的一个成员函数做不到

参数[0]->名称

但是执行此操作的程序确实可以编译和运行。但是,现在我想继承这个类并访问名称字段在这个派生类的 args 数组指针之一中

参数[0]->名称

但这不编译。当我编译下面的示例代码时注释部分未注释,编译器报告:

编译器输出:

g++ test.cc -o 测试

test.cc: 在成员函数'void foo::newnode::print_args2()'中:

test.cc:22: 错误:'std::string foo::node::name' 被保护

test.cc:61: 错误:在此上下文中

编译在 Thu Jun 17 12:40:12 异常退出,代码为 1

问题:

  1. 为什么我可以访问 args 中的节点指针的名称字段类节点,因为这是我希望从类似的在 Java 中定义私有(private)字段。

  2. 如何从派生类访问这些字段。

示例代码:

    #include <iostream>
#include <vector>

using namespace std;

namespace foo
{
class node;
typedef std::vector<node*> nodes;

class node
{
public:
node (string _name);


void print_args ();
void add_node (node* a);

protected:
nodes args;
string name;

};
}

foo::node::node (string _name)
: args(0)
{
name = _name;
}

void foo::node::add_node (node* a)
{
args.push_back(a);
}

void foo::node::print_args ()
{
for (int i = 0; i < args.size(); i++)
{
cout << "node " << i << ": " << args[i]->name << endl;
}
}

// namespace foo
// {
// class newnode : public node
// {
// public:
// newnode (string _name) : node(_name) {}
// void print_args2 ();
// protected:
// };
// }

// void foo::newnode::print_args2 ()
// {
// for (int i = 0; i < args.size(); i++)
// {
// cout << "node " << i << ": " << args[i]->name << endl;
// }
// }

int main (int argc, char** argv)
{
foo::node a ("a");
foo::node b ("b");
foo::node c ("c");
a.add_node (&b);
a.add_node (&c);
a.print_args ();

// foo::newnode newa ("newa");
// foo::newnode newb ("newb");
// foo::newnode newc ("newc");
// newa.add_node (&newb);
// newa.add_node (&newc);
// newa.print_args2 ();

return 0;
}

最佳答案

编译器将允许对象 A 访问对象 B 的私有(private)/ protected 成员,如果 AB 具有相同的静态类型。

我会试着用一个例子来说明这一点:

class Base
{
protected:
int a;
};

class Derived : public Base
{
public:
void foo(Base& b, Derived& d)
{
//allowed because this obviously has the same type as this :)
a = 1;
//allowed because this has the same type as d (Derived)
d.a = 1;
//not allowed because this (Derived) does not have the same
//type as b (Base). They might have the same dynamic type
//but the compiler has no way of knowing this.
b.a = 1;
}
};

所以,回答你的问题:

    如果 args vector 的 node 指针,则
  1. node 类可以访问 name 字段,因为它们也属于 node 类。
  2. 你不能直接。您要么必须公开该字段(我不会那样做),要么公开访问器。

关于c++ protected 指向同一类的指针成员和访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3060572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com