gpt4 book ai didi

c++ - 友元运算符行为(const vs non-const)

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:43 25 4
gpt4 key购买 nike

我有以下 C++ 代码:

#include <iostream>

template <class T>
void assign(T& t1, T& t2) {
std::cout << "First method" << std::endl;
t1 = t2;
}

template <class T>
void assign(T& t1, const T& t2) {
std::cout << "Second method" << std::endl;
t1 = t2;
}

class A {
public:
A(int a) : _a(a) {};
private:
int _a;
friend A operator+(const A& l, const A& r);
};

A operator+(const A& l, const A& r) {
return A(l._a + r._a);
}

int main() {
A a = 1;
const A b = 2;

assign(a, a);
assign(a, b);
assign(a, a+b);
}

输出是:

First method
Second method
Second method

即使我注释掉 main 函数中的前 2 个 assign,输出也保持不变。

有人可以向我解释为什么 operator+ 返回一个 const A 吗?

Linux Debian 64 位和 Windows 7 64 位的输出相同。

最佳答案

它根本不返回 const A。它返回一个临时 A,它只能绑定(bind)到一个 const 引用。

关于c++ - 友元运算符行为(const vs non-const),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7558268/

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