博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c构造函数和析构函数_C ++构造函数和析构函数| 查找输出程序| 套装2
阅读量:2530 次
发布时间:2019-05-11

本文共 2307 字,大约阅读时间需要 7 分钟。

c构造函数和析构函数

Program 1:

程序1:

#include
using namespace std;class Sample{ private: int X; int Y; public: Sample(int x, int y) { X = x; Y = y; } void set(int x, int y) { X = x; Y = y; } void print() { cout<
<<" "<
<

Output:

输出:

main.cpp: In function ‘int main()’:main.cpp:32:12: error: no matching function for call to ‘Sample::Sample()’  Sample S[2];

Explanation:

说明:

The above code will generate a syntax error because in the we created an that must be instantiated by the , but in the class, the default constructor is not defined.

上面的代码将产生语法错误,因为在我们创建了必须由实例化 ,但是在类中,未定义默认构造函数。

Program 2:

程式2:

#include 
using namespace std;class Sample {private: int X; int Y;public: Sample(int x, int y) { X = x; Y = y; } void set(int x, int y) { X = x; Y = y; } void print() { cout << X << " " << Y << endl; }};int main(){ Sample S[2] = { Sample(0, 0), Sample(0, 0) }; Sample* PTR; PTR = S; PTR[0].set(10, 20); PTR[1].set(30, 40); PTR[0].print(); PTR[1].print(); return 0;}

Output:

输出:

10 2030 40

Explanation:

说明:

In the above program, we created a class Sample that contains two X and Y, one , set() and print() member functions. 

在上面的程序中,我们创建了一个Sample类,其中包含两个 XY ,一个 , set()print()成员函数。

Now coming to the main() function, we created an array of objects and that will instantiated by the parameterized constructor. And created a pointer that is being initialized with the base address of array objects. And then called set() and print() functions using the pointer.

现在进入main()函数,我们创建了一个对象数组,该数组将由参数化构造函数实例化。 并创建了一个使用数组对象的基地址初始化的指针。 然后使用指针调用set()print()函数。

Program 3:

程式3:

#include 
using namespace std;class Sample {private: int X;public: Sample() const { } void set(int x) { X = x; } void print() { cout << X << endl; }};int main(){ Sample S; S.set(10); S.print(); return 0;}

Output:

输出:

main.cpp:9:14: error: constructors may not be cv-qualified     Sample() const              ^~~~~

Explanation:

说明:

The above program will generate an error because we cannot as a const member function in C++.

上面的程序将产生错误,因为我们不能在C ++中将函数为const成员函数。

Recommended posts

推荐的帖子

翻译自:

c构造函数和析构函数

转载地址:http://gwxzd.baihongyu.com/

你可能感兴趣的文章
矩阵的SVD分解
查看>>
gitlab的配置
查看>>
linux访问ftp服务器命令
查看>>
ActiveMQ学习笔记之异常
查看>>
LuoguP4012 深海机器人问题(费用流)
查看>>
自动机
查看>>
java知识点
查看>>
WPF设计の画刷(Brush)
查看>>
HTML学习笔记
查看>>
selinux详解及配置文件
查看>>
性能优化之数据库优化
查看>>
Swift - 继承UIView实现自定义可视化组件(附记分牌样例)
查看>>
android自定义viewgroup实现等分格子布局
查看>>
springboot 配置mybatis
查看>>
10慕课网《进击Node.js基础(一)》初识promise
查看>>
JavaScript事件
查看>>
mysql 命令之工作小结
查看>>
linux 系统下 tar 的压缩与解压缩命令
查看>>
阿里负载均衡,配置中间证书问题(在starcom申请免费DV ssl)
查看>>
转:How to force a wordbreaker to be used in Sharepoint Search
查看>>