在C++ 03中,表达式是rvalue或lvalue.
在C++ 11中,表达式可以是:
两类已成为五大类.
考虑以下代码:
struct foo
{
int a;
};
foo q() { foo f; f.a =4; return f;}
int main()
{
foo i;
i.a = 5;
q() = i;
}
Run Code Online (Sandbox Code Playgroud)
没有编译器抱怨它,甚至Clang.为什么q() = ...线路正确?
@FredOverflow在C++聊天室中提到,这this是一个罕见的rvalues具有名称的情况.C++ 0x FDIS提到5.1.1 [expr.prim.general] p4:
否则,如果member-declarator声明类X的非静态数据成员(9.2),则表达式
this是可选的brace-or-equal-initializer 中类型为"指向X的指针"的prvalue.它不应出现在成员声明者的其他地方.(强调我的)
其他人在哪里,如果有的话?
我已经开始学习C ++,目前我正在尝试使用模板,所以,如果我的措辞不是100%准确的,请多多包涵。
我正在使用以下文献:
第一本书看一下下面的模板函数
template<typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(b<a?a:b) {
return b < a ? a : b;
}
Run Code Online (Sandbox Code Playgroud)
并指出,这个定义有一个缺点,因为T1或者T2可能是一个参考,因此,返回类型可以是引用类型。
但是,第二本书指出,如果ParamType在我们的情况下T1,T2既不是指针也不是引用(对于我们的情况而言如此),则调用表达式的引用部分将被忽略。
举例说明
template<typename T>
void f(T param);
int x = 27; // as before
const int cx = x; // as before
const int& rx = x; // as before
f(x); // T's and param's types …Run Code Online (Sandbox Code Playgroud) c++ templates reference decltype template-argument-deduction
假设我有一个非常简单的课程
class C {
private:
int _a;
int _b;
public:
C (int a, int b) :_a { a }, _b { b } {}
int a () { return _a; }
int b () { return _b; }
bool operator== (C c) {
return this->_a == c.a() && this->_b == c.b();
}
};
Run Code Online (Sandbox Code Playgroud)
我想重载操作+=,使得
C foo(8, 42);
C bar(1, 1);
C zoo(9, 43);
foo += bar;
assert(foo == zoo);
Run Code Online (Sandbox Code Playgroud)
运行正常.
至于我读过其他人的代码,我应该写一些类似的东西
C operator+= (C c) {
return { …Run Code Online (Sandbox Code Playgroud) c++ ×5
c++11 ×2
c++-faq ×1
decltype ×1
expression ×1
lvalue ×1
named ×1
reference ×1
return-value ×1
rvalue ×1
template-argument-deduction ×1
templates ×1