区分三种不同的对象构造方式
2007-01-03 20:44
253 查看
由一个类构造一个对象有多种构造方式,以下代码展示各种构造方式:
class Int
...{
public:
Int()
...{
cout << "Default Constructor" << endl;
}
Int(int a) : a_(a)
...{
cout << "Direct Constructor" << endl;
}
Int(const Int& other)
...{
cout << "Copy Constructor" << endl;
a_ = other.a_;
}
Int& operator =(const Int& other)
...{
cout << "Copy Assign Operator" << endl;
a_ = other.a_;
return *this;
}
private:
int a_;
};
int main(int argc, char* argv[])
...{
int u = 10;
cout << "Int t1: ";
Int t1;
cout << "Int t2(): Prototyped Function" << endl;
Int t2();
cout << "Int t3(u): ";
Int t3(u);
cout << "Int t4 = u: ";
Int t4 = u;
cout << "Int t5(t4): ";
Int t5(t4);
cout << "Int t6 = t4: ";
Int t6 = t4;
cout << "t1 = t4: ";
t1 = t4;
return getchar();
}
下面是运行后的结果:
Int t1: Default Constructor
Int t2(): Prototyped Function
Int t3(u): Direct Constructor
Int t4 = u: Direct Constructor
Int t5(t4): Copy Constructor
Int t6 = t4: Copy Constructor
t1 = t4: Copy Assign Operator
class Int
...{
public:
Int()
...{
cout << "Default Constructor" << endl;
}
Int(int a) : a_(a)
...{
cout << "Direct Constructor" << endl;
}
Int(const Int& other)
...{
cout << "Copy Constructor" << endl;
a_ = other.a_;
}
Int& operator =(const Int& other)
...{
cout << "Copy Assign Operator" << endl;
a_ = other.a_;
return *this;
}
private:
int a_;
};
int main(int argc, char* argv[])
...{
int u = 10;
cout << "Int t1: ";
Int t1;
cout << "Int t2(): Prototyped Function" << endl;
Int t2();
cout << "Int t3(u): ";
Int t3(u);
cout << "Int t4 = u: ";
Int t4 = u;
cout << "Int t5(t4): ";
Int t5(t4);
cout << "Int t6 = t4: ";
Int t6 = t4;
cout << "t1 = t4: ";
t1 = t4;
return getchar();
}
下面是运行后的结果:
Int t1: Default Constructor
Int t2(): Prototyped Function
Int t3(u): Direct Constructor
Int t4 = u: Direct Constructor
Int t5(t4): Copy Constructor
Int t6 = t4: Copy Constructor
t1 = t4: Copy Assign Operator
相关文章推荐
- Js构造对象-添加方法的三种方式
- Js构造对象-添加方法的三种方式
- js 对象克隆的三种方式
- WebSocket不同版本的三种握手方式以及一个Netty实现JAVA类
- Spring IoC Service Provicer 管理对象间的依赖关系的三种方式
- 《黑马程序员》 字节码文件对象获取的三种方式
- Windows10-UWP中设备序列显示不同XAML的三种方式[3]
- 不同vlan间通信的三种配置方式
- 再次区分xcode add文件的三种方式
- Java创建对象的方式和C++有什么不同
- WebSocket不同版本的三种握手方式以及一个Netty实现JAVA类
- 使用DataSet Datatable 更新数据库的三种方式及DataTable不同状态的取值
- 实现ListView 三种不同布局的加载的方式
- MFC三种不同方式实现图形的保存和重绘---方法二: 运用CMetaFileDC
- Intelli JDEA 创建Scala项目的三种不同方式
- 28-反射机制-03-反射机制(获取Class对象的三种方式)
- js 创建对象的三种方式——工厂模式、构造函数模式、原型模式
- C#中对象的销毁有三种方式Finalize,Dispose,GC。请大虾们描述三种方式的区别啊?/java中的析构函数
- Java:创建Class对象的三种方式/
- Spring DI依赖注入setter,构造,注解,三种依赖方式的总结