#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Complex{
public:
double real, imag;
Complex(int i){
cout << "IntConstructor called" << endl;
real = i; imag = 0;
}
Complex(double r, double i){
real = r;
imag = i;
}
};
int main()
{
Complex c1(7, 8);
Complex c2 = 12;
c1 = 9;
cout << c1.real << "," << c1.imag << endl;
return 0;
}
运行结果:
IntConstructor called
IntConstructor called
9,0

本文介绍了一个C++类`Complex`的构造函数实现,探讨了如何使用不同构造函数初始化复数对象,并展示了main函数中对象的创建和输出。重点在于理解构造函数的调用和类变量的初始化过程。

被折叠的 条评论
为什么被折叠?



