有以下代碼,爲什麼第一個賦值不會在Foo
中調用模板operator=
,但第二個呢?這裏發生了什麼?即使用戶定義的模板存在,是否有編譯器爲第一個賦值生成的?使用模板賦值運算符
#include <iostream>
using namespace std;
struct UberFoo { };
struct Foo : public UberFoo
{
template<typename T> void operator=(const T& v) { cout << "const T&" << endl; Set(v); }
template<typename T> void operator=(T& v) { cout << "T&" << endl; return Set(v); }
virtual void Set(const Foo&) { cout << "Foo::Set(const Foo&)" << endl; }
virtual void Set(const UberFoo&) { cout << "Foo::Set(const UberFoo&)" << endl; }
};
struct Bar : public Foo
{
virtual void Set(const Foo&) { cout << "Bar::Set(const Foo&)" << endl; }
virtual void Set(const UberFoo&) { cout << "Bar::Set(const UberFoo&)" << endl; }
};
int main()
{
Bar a, b;
Foo & pa = a;
const Foo& rb = b;
const UberFoo & urb = b;
cout << "First" << endl;
pa = rb;
cout << endl << "Second" << endl;
pa = urb;
return 0;
}
我知道賦值運算符應該返回參考自我(做鏈接可能),但這不是重點 – relaxxx
是的,一個拷貝賦值運算符始終定義,除非明確地刪除。如果你沒有定義一個,編譯器會。 –