使用 structType*& 赋给结构成员
Assigning to struct member using structType*&
我对指针没问题,但是在这个程序中处理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
对象的指针的引用。
相关文章:
- 具有结构成员char数组的sscanf
- 仅使用结构名称访问结构成员
- 使用 structType*& 赋给结构成员
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 是否可以将结构数组别名为结构成员数组?
- 结构成员在访问时被清除
- 如何指示结构成员没有锯齿?
- 为什么继承的结构成员在联合中无法访问?
- 尝试在 qml 中访问结构成员的 QList
- C++/CLI -- 访问结构成员
- 调用在类中声明的结构成员
- 对结构成员的临时绑定引用
- 无法使用 strcpy 将字符串复制到静态结构成员
- 为什么类成员数据必须是静态的才能被模板化类的模板化结构成员访问
- 填充模板化结构类型的结构成员
- C/C++intellisense 0.26.1不显示结构成员列表
- 在源文件中创建具有结构成员的结构
- 如何访问结构成员作为指针