【发布时间】:2015-11-26 09:39:50
【问题描述】:
#include <iostream>
using namespace std;
class B{
public:
int date;
B(){cout<<"B()"<<endl;}
B(int a){date=a;cout<<"B(int a)"<<endl;}
B(const B& b){
date=b.date;
cout<<"int date;"<<endl;
}
B& operator =(const B& b){
date=b.date;
cout<<"operator(const B& b)"<<endl;
return *this;
}
void print(){
std::cout<<date<<std::endl;
}
};
int main(){
B a(1);//use B(int a)
B* b;
B* c;
*b=a;//use operator(const B& b)
*c=*b;//but this one is wrong,why?,I think it also use operator(const B& b)
new (c)B(*b);
return 0;
}
当我使用*c=*b时它不起作用,我认为它也使用operator(const B& b),但是当我使用new(c)B(*b)时它就可以了。
*c=*b和new(c)B(*b)有什么区别,为什么*c=*b错了?
【问题讨论】:
-
它是如何不起作用的?您的指针此时尚未初始化,这可能会导致未定义的行为。
-
所有使用指针
b和c的表达式会导致未定义的行为,因为b和c是未初始化.
标签: c++