本文共 2307 字,大约阅读时间需要 7 分钟。
c构造函数和析构函数
Program 1:
程序1:
#includeusing 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:
#includeusing 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类,其中包含两个 X和Y ,一个 , 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:
#includeusing 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/