1
我有一个类的定义。我对一些构造函数的行为感到困惑。以下是代码。为什么构造函数在某些情况下不起作用?
#include <iostream>
#include <cstdlib>
using namespace std;
class A
{
int i;
public:
void seti(int v) {cout << "Setting i\n"; i=v;}
void print() {cout << "i = " << i << endl;}
A(){};
A(int v) {cout << "Setting i in par-ctor to " << v << "\n"; i=v;}
A(A& o) {cout << "In copy ctor, changing i to " << o.i << "\n";i=o.i;}
A& operator=(A o) {cout << "In assignment op\n"; this->i = o.i; return(*this);}
};
int main()
{
A o1;
A o2(2);
A o3 = A(4);
A o4 = 35;
return(0);
}
我想知道为什么此代码不能编译,除非
一)定义的拷贝构造函数被注释,或
B)所定义的拷贝构造函数有一个'const'
限定符的A& A(const A& o)
或
c)o3和o4的对象初始化都被删除。
关于(c)在构造函数A(INT)的调用预计,
如何进行实际拷贝构造函数定义(一个没有const
)冲突与参数化(使用int)构造?
谢谢!完全有意义。 – anupamb
@anupamb不要忘记接受,如果你认为它是正确的。 –