使用 structType*& 赋给结构成员

Assigning to struct member using structType*&

本文关键字:结构 成员 structType 使用      更新时间:2023-10-16

我对指针没问题,但是在这个程序中处理test*&t时感到困惑。我的理解可能是不正确的,是t包含root的地址,而root本身是指向类型test的未声明(?(结构的指针。我明白错误的含义。我基本上是在说 0="abc",但我不确定通过使用读取函数通过 t 为 root.detailText 分配新值的正确方法。我无法更改读取功能主体之外的任何内容。

测试.cpp我收到错误的文件。

void test::read (istream& in, test*& t)
{
cout<<"test "<<&t->detailText<<" test";
if (&t->detailText == 0){ // Works fine.
&t->detailText = "abc"; //error: lvalue required as left operand of assignment
}
}

测试.h

struct test {
std::string detailText;
test* ifYes;
test* ifNo;
test (std::string q, test* yes = NULL, test* no = NULL)
: detailText(q), ifYes(yes), ifNo(no)
{}
static void read (std::istream& in, test*& t);
static void write (std::ostream& out, const test* root);

private:
friend std::istream& operator>> (std::istream&, test*&);
friend std::ostream& operator<< (std::ostream&, const test*);
};
inline
std::istream& operator>> (std::istream& in, test*& n)
{
test::read (in, n);
return in;
}

开始读取过程的其他文件

test* root = 0;
{
ifstream in (fileName);
if (in.good())
in >> root;
}

...在此程序中处理test*&t时。我的理解可能是不正确的,是 t 包含根的地址,而根本身是指向类型测试的未声明(?

root本身就是一个test*,这是正确的。但t是对root引用,而不是root的地址。所以你应该像使用root一样使用t,并注意修改t会修改root

所以在你的函数中,你根本不应该使用&。您只需要:

void test::read (istream& in, test*& t)
{
if (t != nullptr) { 
cout<<"test "<< t->detailText << " test";
t->detailText = "abc"; 
}
}

请注意,在取消引用它以查看detailText之前,您应该检查t是否是有效的指针。

关于类型的混淆是学习C++时的常见问题。我发现从右到左阅读更容易。

鉴于

test*& t

如果你从右到左读,它会读成

t是对指向test对象的指针的引用。