本文主要是介绍C++通过引用来传递和返回类对象(四十二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.代码示例
/*C++通过引用来传递和返回类对象*/
#include <iostream>
using namespace std;class MacBook{
public://定义void setprice(double p);double getprice();void settitle(char * p);char * gettitle();private:double price;char * title;
};//实现
void MacBook::setprice(double p){price = p;
}double MacBook::getprice(){return price;
}
void MacBook::settitle(char * p){title = p;
}char * MacBook::gettitle(){return title;
}//显示
void display(MacBook & b)
{cout << b.gettitle() << "的价钱为: " << b.getprice() <<" RMB"<<endl;
}MacBook & init(char *t,double p)//通过引用返回对象
{static MacBook b;b.setprice(p);b.settitle(t);return b;
}int main(){MacBook Alan;char c[20] = {0};string s = "Mac2016款";memcpy(c,s.c_str(),strlen(s.c_str()));//string->char*Alan = init(c,10800);display(Alan);return 0;
}
这篇关于C++通过引用来传递和返回类对象(四十二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!