gpt4 book ai didi

c++ - 在这种情况下如何测试左值或右值

转载 作者:搜寻专家 更新时间:2023-10-30 23:59:29 25 4
gpt4 key购买 nike

代码如下:

struct A
{
static int k;
  int i;
};
 
int A::k = 10;
 
A func() { A a; return a; }

我的问题是,如何判断 func().kfunc().i 是否为左值?如果两者都是左值/右值,我该如何测试它们?

func().k = 0; // compile ok under g++-4.4 and g++-4.6
func().i = 1; // compile ok with g++-4.4, but g++-4.4 gives an error:
//"using temporary as lvalue [-fpermissive]"

最佳答案

func().k 是一个左值,而 func().i 是一个 xvalue。

您可以查看更多详细信息: rvalues and temporary objects in the FCD

自始至终,不难判断它们是左值还是右值:

#include <iostream>

struct A
{
static int k;
int i;
};

int A::k = 10;

A func( ){ A a; return a; }

void f (int & ) { std::cout << "int& " << std::endl; }

int main ()
{
func().k = 0; //ok, because func().k is an r
f(func().k);
func().i = 1; //compile error: "using temporary as lvalue"
f(func().i); //compile error because func().i is an rvalue of type ‘int’
return 0;
}

关于c++ - 在这种情况下如何测试左值或右值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16346068/

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