1.函数返回值为指针或者引用
在函数中新建对象实例和结构体实例时,如果函数返回值为指针或者引用类型时,在函数中创建对象变量时,应使用new或者malloc进行动态分配内存,否则,返回的指针或引用都将指向同一个变量。
具体示例可见如下:
class myOperator
{
public:
myOperator(double r = 0.0, double i = 0.0)
{
real = r;
image = i;
}
//返回值为指针
myOperator *test();
public:
double real;
double image;
};
myOperator* myOperator:: test()
{
myOperator my(1,2);
return &my;
}
myOperator* test()
{
myOperator my(1,2);
return &my;
}
int main()
{
myOperator my1(1.0, 2.0), my2(2.0, 3.0);
myOperator* m1, * m2, * m3, * m4, * m5, * m6;//可以使用指针数组,前面测试用了指针就再没建数组,加[]麻烦……
cout << "类里的test()函数" << endl << "my1调用" << endl;
m1 = my1.test();
m2 = my1.test();
cout << m1<<endl;
cout << m2 << endl;
cout << "my2调用" << endl;
m3 = my2.test();
m4 = my2.test();
cout << m3 << endl;
cout << m4 << endl;
cout << "类外的test()函数" << endl;
m5 = test();
m6 = test();
cout << m5 << endl;
cout << m6 << endl;
}
//输出如下:
类里的test()函数
my1调用
00EFF864
00EFF864
my2调用
00EFF864
00EFF864
类外的test()函数
00EFF870
00EFF870
由此可见,同一个类的所有对象调用test()函数返回的指针都指向了内存中同一个myOperator对象,类外的test()函数调用时,也同理,指向的是同一个myOperator对象。
2.函数返回值为对象
函数返回值为对象时,可直接创建局部变量,并返回,在返回时,会自动新建一个对象。
修改上述代码中test函数的部分,以及修改类中test的声明为
myOperator test();
myOperator myOperator:: test()
{
myOperator my(1,2);
return my;
}
myOperator test()
{
myOperator my(1,2);
return my;
}
//输出如下:
类里的test()函数
my1调用
006FF8FC
006FF8E4
my2调用
006FF8CC
006FF8B4
类外的test()函数
006FF89C
006FF884
可见,返回的都是新建立的对象,因此直接返回对象是可行的,通过拷贝构造函数返回原对象的拷贝。
3.关于cout直接输出地址时的一些坑
使用第1部分的test()函数即
myOperator* test()
{
myOperator my(1,2);
return &my;
}
并在主函数中进行输出test()
m1 = test();
cout << m1 << endl;
cout << test() << endl;
cout << test() << endl << endl;
cout << test() << endl << endl << endl;
//输出如下:
008BF8A4
008BF8A0
008BF89C
008BF898
发现在直接输出地址时,会将后面的endl也计算进去,输出指针m1则不会。