为什么此代码不打印“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;
}
为什么此代码不打印“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";
}
};
将打印“拷贝赋值”和基本上等于什么编译器会为您(不印刷,课程)。
因为它只是一个赋值运算符,所以不会阻止编译器隐式生成_copy-assignment_运算符,这是实际在此调用的。 – ildjarn