gpt4 book ai didi

c++ - 为什么模板运算符重载不起作用?

转载 作者:行者123 更新时间:2023-11-30 00:39:20 25 4
gpt4 key购买 nike

为什么这段代码不打印“operator=”?

#include <iostream>
using namespace std;

class A{
public:
template<typename T> void operator=(const T& other){
cout<<"operator="<<endl;
}
};

int main(){
A a;
A b;
a=b;
}

最佳答案

编译器生成的复制赋值运算符由重载决议选择:

class A{
public:
A& operator=(A const& other){
std::cout << "copy assignment\n";
return *this;
}
template<class T>
void operator=(T const& other){
std::cout << "templated assignment\n";
}
};

将打印“复制赋值”并且基本上等于编译器将为您生成的内容(当然不打印)。

关于c++ - 为什么模板运算符重载不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9010502/

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