作为一个经验丰富的编程人员,想必对C++编程语言一定有所了解。因为这一语言已经成为开发领域中一个重要的应用语言。下面大家可以根据本文对C++赋值函数的理解,进一步加深对C++语言的了解程度。

创新互联建站专业为企业提供吴堡网站建设、吴堡做网站、吴堡网站设计、吴堡网站制作等企业网站建设、网页设计与制作、吴堡企业网站模板建站服务,十载吴堡做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
C++的拷贝函数和C++赋值函数既有联系又有区别,不细究的话很容易搞混,遂以小例示之如下,权作解惑之用。
C++赋值函数相关代码示例:
- // test.cpp
 - #include
 - #include
 - #include
 - using namespace std;
 - class Book
 - {
 - public:
 - Book(const char *name, const char*author, const double price):
 
price(price) {- this->name = new char[strlen(name)+1];
 - this->author = new char[strlen(author)+1];
 - strcpy(this->name, name);
 - strcpy(this->author,author);
 - }
 - Book(const Book& book){
 - name = new char[strlen(book.name)+1];
 - author = new char[strlen(book.author)+1];
 - price = book.price;
 - strcpy(name, book.name);
 - strcpy(author, book.author);
 - }
 
- Book& operator=(const Book& rhs) {
 - Book(rhs).swap(*this); // 先创建临时对象Book(rhs),
 
再调用下面的swap进行数据交换,- // 注意与*this交换数据的是临时对象, rhs并未修改,只是swap
 - // 结束后临时对象拥有了*this的数据, 而*this也拥有了由rhs
 - // 构造的临时对象的数据, 临时对象生命期结束时,*this的数据
 - // 会被销毁。
 - return *this;
 - }
 - ~Book(){
 - delete[] name;
 - delete[] author;
 - }
 - private:
 - Book& swap(Book& rhs) {
 - double temp = rhs.price;
 - rhs.price = price;
 - price = temp;
 - std::swap(name, rhs.name);
 
// std::swap()只是简单的交换指针的值- std::swap(author, rhs.author);
 - return *this;
 - }
 - public:
 - char* name;
 - char* author;
 - double price;
 - };
 - int main() {
 - Book a("The C++ standard library", "Nicolai M. Josuttis", 98);
 - Book b = a; // 对象b不存在, 拷贝构造函数在这里被调用
 - Book c("Emacs Lisp manual", "stallman", 0);
 - c = a; // c对象已经存在, C++赋值函数(operator=)在这里被调用
 - cout << a.name << endl;
 - cout << a.author << endl;
 - cout << a.price << endl << endl;
 - cout << b.name << endl;
 - cout << b.author << endl;
 - cout << b.price << endl << endl;
 - cout << c.name << endl;
 - cout << c.author << endl;
 - cout << c.price << endl;
 - }
 
编译:
- g++ -o test test.cpp
 
运行结果:
- The C++ standard library
 - Nicolai M. Josuttis
 - 98
 - The C++ standard library
 - Nicolai M. Josuttis
 - 98
 - The C++ standard library
 - Nicolai M. Josuttis
 - 98
 
以上就是对C++赋值函数的相关介绍。
                分享题目:C++赋值函数代码详解
                
                路径分享:http://www.csdahua.cn/qtweb/news10/135760.html
            
成都网站优化推广公司_创新互联,为您提供建站公司、网站营销、App开发、ChatGPT、网站收录、关键词优化
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网