我是编程新手.对不起,我的英语不好.我试图使用rvalue作为初始对象的初始化器.因此,根据代码,它将打印出使用的构造函数和赋值运算符.但结果是对象"what2"和"what3",那些不打印任何东西.这是代码:
#includeusing namespace std; class X{ public: int x; X()= default; X(int num):x{num}{} X(const X& y){ x = y.x; std::cout << "copy constructor" << std::endl; std::cout << x << std::endl; } X& operator=(const X& d){ x = d.x; std::cout << "copy assignment" << std::endl; return *this; } X(X&& y){ x = y.x; std::cout << "move constructor" << std::endl; } X& operator=(X&& b){ x = b.x; std::cout << "move assignment" << std::endl; return *this; } }; X operator +(const X& a,const X& b){ X tmp{}; tmp.x = a.x +b.x; return tmp; } int main(int argc, const char * argv[]) { X a{7} , b{11}; X what1; cout << "---------------" << endl; what1 = a+b; cout << "---------------" << endl; X what2{a+b}; cout << "---------------" << endl; X what3 = a+b; cout << "---------------" << endl; std::cout << what1.x << std::endl; std::cout << what2.x << std:: endl; std::cout < 输出是:
--------------- move assignment --------------- --------------- --------------- 18 18 18 Program ended with exit code: 0只有"what1"正确使用赋值.那么,我如何使用rvalue初始化一个对象?并使用operator =来初始化一个对象?非常感谢你.